Javascript Date - javascript

I am trying to get a month range to insert into a CAML query, ie: 2010-09-01 and 2010-09-30.
I have used the following code to generate these two values:
var month = "10/2010";
var monthArray = month.split("/");
var startDate = new Date(monthArray[1], monthArray[0]-1, 1);
var endDate = new Date(startDate);
endDate.setMonth(startDate.getMonth()+1, startDate.getDate()-1);
Running this code:
alert("month: " + month +
"\nstartDate: " + startDate.toDateString() +
"\nendDate: " + endDate.toDateString());
generates the correct dates (corporate policy requires IE7):
---------------------------
Windows Internet Explorer
---------------------------
month: 10/2010
startDate: Fri Oct 1 2010
endDate: Sun Oct 31 2010
---------------------------
OK
---------------------------
However, when I attempt to parse into ISO 8601 format (for the CAML query), I get the wrong dates.
var endISO8601 = endDate.getUTCFullYear() + "-" +
endDate.getUTCMonth() + "-" +
endDate.getUTCDate() + "T19:59:00Z";
alert("endDate: " + endDate.toDateString() +
"\nendISO8601: " + endISO8601);
---------------------------
Windows Internet Explorer
---------------------------
endDate: Sun Oct 31 2010
endISO8601: 2010-9-31T19:59:00Z
---------------------------
OK
---------------------------
I am not allowed to use Datejs, unfortunately.

I think you are just forgetting to add one to the month (january is 0 in javascript)

Related

Google sheet / javascript not evaluating dates as expected

I have a PHP script that records a timestamp in a Google Sheet. When I tried to see if this timestamp is between two other timestamps that I have entered manually into the same sheet, I discovered some odd behavior. I thought it might be because Google added a ' at the start of the string in the cell so I tried doing a substr to remove the apostrophe.
function weirdDate(dateFromPhp) {
var dateSubStr = new Date(dateFromPhp.substr(1));
var dateDefault = new Date(dateFromPhp);
return "dateFromPhp: " + dateFromPhp + " dateSubStr: " + dateSubStr + " dateDefault: " + dateDefault;
}
Output is:
dateFromPhp: 16/01/2020 08:33:45
dateSubStr: Mon Jun 01 2020 08:33:45 GMT+1000 (AEST)
dateDefault: Thu Apr 01 2021 08:33:45 GMT+1100 (AEDT)
I have no idea why these dates are months or years away from the expected and with different timezones. The operation without the substr resulted in the correct timezone for me.
Any idea how I can make this string into a timestamp with the correct date?
I discovered the answer. I had no idea javascript expected mm/dd/yyyy as the order for the date format.
function weirdDate(dateFromPhp) {
var dateSubStr = new Date(dateFromPhp.substr(1));
var dateDefault = new Date(dateFromPhp);
var dateUs = americanizeDate(dateFromPhp);
return "dateFromPhp: " + dateFromPhp + " dateSubStr: " + dateSubStr + " dateDefault: " + dateDefault + " dateUS: " + dateUs;
}
function americanizeDate(ausDate) {
var dateParts = ausDate.split("/");
// month is 0-based, that's why we need dataParts[1] - 1
var usDate = new Date(dateParts[1]+"/"+dateParts[0]+"/"+ dateParts[2]);
return usDate;
}
Switching the month and the day solved the problem.

Date.toISOString() but local time instead of UTC

Let's say we have this datetime:
var d = new Date("Sat Jul 21 2018 14:00:00 GMT+0200");
Exporting it as a string (console.log(d)) gives inconsistent results among browsers:
Sat Jul 21 2018 14:00:00 GMT+0200 (Paris, Madrid (heure d’été)) with Chrome
Sat Jul 21 14:00:00 UTC+0200 2018 with Internet Explorer, etc.
so we can't send datetime to a server with an unconsistent format.
The natural idea then would be to ask for an ISO8601 datetime, and use d.toISOString(); but it gives the UTC datetime: 2018-07-21T12:00:00.000Z whereas I would like the local-timezone time instead:
2018-07-21T14:00:00+0200
or
2018-07-21T14:00:00
How to get this (without relying on a third party dependency like momentjs)?
I tried this, which seems to work, but isn't there a more natural way to do it?
var pad = function(i) { return (i < 10) ? '0' + i : i; };
var d = new Date("Sat Jul 21 2018 14:00:00 GMT+0200");
Y = d.getFullYear();
m = d.getMonth() + 1;
D = d.getDate();
H = d.getHours();
M = d.getMinutes();
S = d.getSeconds();
s = Y + '-' + pad(m) + '-' + pad(D) + 'T' + pad(H) + ':' + pad(M) + ':' + pad(S);
console.log(s);
There is limited built-in support for formatting date strings with timezones in ECMA-262, there is either implementation dependent toString and toLocaleString methods or toISOString, which is always UTC. It would be good if toISOString allowed a parameter to specify UTC or local offset (where the default is UTC).
Writing your own function to generate an ISO 8601 compliant timestamp with local offset isn't difficult:
function toISOLocal(d) {
var z = n => ('0' + n).slice(-2);
var zz = n => ('00' + n).slice(-3);
var off = d.getTimezoneOffset();
var sign = off > 0? '-' : '+';
off = Math.abs(off);
return d.getFullYear() + '-'
+ z(d.getMonth()+1) + '-' +
z(d.getDate()) + 'T' +
z(d.getHours()) + ':' +
z(d.getMinutes()) + ':' +
z(d.getSeconds()) + '.' +
zz(d.getMilliseconds()) +
sign + z(off/60|0) + ':' + z(off%60);
}
console.log(toISOLocal(new Date()));
The trick is to adjust the time by the timezone, and then use toISOString(). You can do this by creating a new date with the original time and subtracting by the timezone offssetfrom the original time:
var d = new Date("Sat Jul 21 2018 14:00:00 GMT+0200");
var newd = new Date(d.getTime() - d.getTimezoneOffset()*60000);
console.log(newd.toISOString()); // 2018-07-21T22:00:00.000Z
Alternatively, you can simply adjust the original date variable:
var d = new Date("Sat Jul 21 2018 14:00:00 GMT+0200");
d = new Date(d.getTime() - d.getTimezoneOffset()*60000);
console.log(d.toISOString()); // 2018-07-21T22:00:00.000Z
For your convenience, the result from .getTime() is the number of milliseconds since 1 January 1970. However, getTimezoneOffset() gives a time zone difference from UTC in minutes; that’s why you need to multiply by 60000 to get this in milliseconds.
Of course, the new time is still relative to UTC, so you’ll have to ignore the Z at the end:
d = d.slice(0,-1); // 2018-07-21T22:00:00.000
My version:
// https://stackoverflow.com/questions/10830357/javascript-toisostring-ignores-timezone-offset/37661393#37661393
// https://stackoverflow.com/questions/49330139/date-toisostring-but-local-time-instead-of-utc/49332027#49332027
function toISOLocal(d) {
const z = n => ('0' + n).slice(-2);
let off = d.getTimezoneOffset();
const sign = off < 0 ? '+' : '-';
off = Math.abs(off);
return new Date(d.getTime() - (d.getTimezoneOffset() * 60000)).toISOString().slice(0, -1) + sign + z(off / 60 | 0) + ':' + z(off % 60);
}
console.log(toISOLocal(new Date()));
i have found a solution which has worked for me.
see this post: Modifying an ISO Date in Javascript
for myself i tested this with slight modification to remove the "T", and it is working. here is the code i am using:
// Create date at UMT-0
var date = new Date();
// Modify the UMT + 2 hours
date.setHours(date.getHours() + 2);
// Reformat the timestamp without the "T", as YYYY-MM-DD hh:mm:ss
var timestamp = date.toISOString().replace("T", " ").split(".")[0];
and an alternative method is stipulate the format you need, like this:
// Create the timestamp format
var timeStamp = Utilities.formatDate(new Date(), "GMT+2", "yyyy-MM-dd' 'HH:mm:ss");
note: these are suitable in locations that do not have daylight saving changes to the time during the year
it has been pointed out that the above formulas are for a specific timezone.
in order to have the local time in ISO format, first specify suitable Locale ("sv-SE" is the closest and easiest to modify), then make modification (change the space to a T) to be same as ISO format. like this:
var date = new Date(); // Create date
var timestamp = date.toLocaleString("sv-SE").replace(" ", "T").split(".")[0]; // Reformat the Locale timestamp ISO YYYY-MM-DDThh:mm:ss
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString)
https://www.w3schools.com/Jsref/jsref_tolocalestring.asp
https://www.w3schools.com/Jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all

Format dates in Javascript

I have to log my error with datetime in some file, for that I am using following code:
var dLogDate = new Date();
console.log(dLogDate.toString().substring(4) + ', ' + dLogDate.toGMTString().substring(4));
as per above code output comes as follows which is nice but not formated as I need:
"Oct 10 2014 12:48:59 GMT+0530 (IST), 10 Oct 2014 07:18:59 GMT"
I want result s follows :
"10 Oct 2014 12:48:59 (IST), 10 Oct 2014 07:18:59 (GMT)"
see date part before ",". I need 10 Oct instated of Oct 10
This can be done with some function which is substring first 4 character from string and concat at 3rd position again, But I am still curious to know if there are any other simple way to do this? I don't want to use any third party library/script.
Thanks.
You could try adding to the prototype an extension method toISTString
function pad(n) {
return (n < 10) ? '0' + n : n;
}
Date.prototype.toISTString = function(locale) {
var year = this.getFullYear().toString();
var month = this.toLocaleString(locale, { month: "short" }) // ECMAScript Internationalization API, which is very new only available in Blink browsers (Chrome and Opera), IE11, and Firefox 29+.
var day = this.getDate().toString();
var hrs = this.getHours().toString();
var mins = this.getMinutes().toString();
var secs = this.getSeconds().toString();
return day + " " + month + " " + year + " " + pad(hrs) + ":" + pad(mins) + ":" + secs + " (IST)";
};
dLogDate = new Date();
console.log(dLogDate.toISTString("en-us") + ', ' + dLogDate.toGMTString().substring(4));
JSFiddle
You can use date functions to format date
http://www.w3schools.com/jsref/jsref_obj_date.asp
var monthIndex = date.getMonth();
var dayIndex = date.getDay();
var monthArray = ['January',....];
var dayArray = ['Sunday',...]
console.log(monthArray[monthIndex] + "-" + dayArray[dayIndex]);

Javascript date formatting Fri Jun 21 00:00:00 UTC+0100 2013 to iso 8601 (2013-06-21)

Please advise:
Is there a way without regex or string replaces and so forth to convert a simple date such as:
Fri Jun 21 00:00:00 UTC+0100 2013
To a ISO8601 formatted date yy-mm-dd?
PS: 8601 date only, not date time.
Use moment.js http://momentjs.com/
moment(new Date(), "YYYY-MM-DD HH:mm Z");
or:
var date = moment("Fri Jun 21 00:00:00 UTC+0100 2013");
moment("Fri Jun 21 00:00:00 UTC+0100 2013", "YYYY-MM-DD HH:mm Z");
You can parse it and format it very easily whatever way you want http://momentjs.com/docs/ it is compatible with ISO-8601 dates for parsing as well.
Yes !
the date function in javascript.
var d = new Date("Fri Jun 21 00:00:00 UTC+0100 2013")
alert( d.getFullYear() + '-' + d.getUTCMonth() + '-' + d.getUTCDay())
2 lines of code :)
more info here : http://www.w3schools.com/jsref/jsref_obj_date.asp
Without regexes or string replaces? Yes, assuming that the format is fixed you could use .slice() and/or .substr() to extract the particular bits you need and rearrange them (unless such methods fall into your category of "and so forth"):
var input = "Fri Jun 21 00:00:00 UTC+0100 2013";
var year = input.slice(-4),
month = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'].indexOf(input.substr(4,3))+1,
day = input.substr(8,2);
var output = year + '-' + (month<10?'0':'') + month + '-' + day;
Or you could go ahead and get silly with a regex replace:
var output = input.replace(/^[^\s]+\s([^\s]+)\s(\d+)\s.*(\d{4})$/,function(m,p1,p2,p3) {
var month = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'].indexOf(p1)+1;
return p3 + '-' + (month<10?'0':'') + month + '-' + (p2.length===1?'0':'') + p2;
});
Of course you'd probably want to wrap such code in a reformatDate() method.
(For a "simple" reformatting of a date string, the Date object and its methods aren't particularly helpful unless the starting format is one recognised by Date.parse().)
Why dont you try to use the get functions, like getDate(), getMonth(), etc. For example:
var today = new Date();
var d1 = new Date();
alert(d1);
var date = d1.getDate();
var month = d1.getMonth() + 1;
var year = d1.getFullYear();
Then configure the string the way you want it to appear...!

Convert RFC 822 date to valid Date for javascript

I'm using a script calendar that when I choose a date, it convert it to a new format (yyyy-mm-dd)
It works in most browser but in Firefox and Opera, I get an invalid date format because the format i work with is RFC 822.
I'm looking for a way to convert this date format
example:
Thu Sep 08 2011 12:00:00 GMT-0400 (EDT)
and change it to
2011-09-08
Could that be done in javascript ?
UPDATE
Here's my code trying to replace the (EDT) to nothing
$(".taskDate").datepick({
onSelect: function(selectedDate){
selectedDate = selectedDate.replace(/ \(.+\)/, '');
//alert(selectedDate);
var newDate = new Date(selectedDate);
$(".selectedDate").text(newDate.getFullYear()+'-'+(newDate.getMonth()+1)+'-'+newDate.getDate());
location.href="index.php?date="+newDate.getFullYear()+'-'+(newDate.getMonth()+1)+'-'+newDate.getDate();
}
});
Now I get an error
selectedDate.replace is not a function
How come ?
UPDATE 2
Fixed it because it seems that it was an object and not a darn string.
Added
selectedDate = selectedDate.toString();
before the new Date();
Now it's working for all browsers...
Works in Firefox6, see my jsfiddle.
var sOriginalDate = 'Thu Sep 08 2011 12:00:00 GMT-0400 (EDT)';
var oDate = new Date(sOriginalDate);
var iMonth = oDate.getMonth() + 1;
var iDay = oDate.getDate();
var sNewDate = oDate.getFullYear() + '-'
+ (iMonth < 10 ? '0' : '') + iMonth + '-'
+ (iDay < 10 ? '0' : '') + iDay;
alert(sNewDate);
Since the date is RFC 822 you could parse it to a valid Date (the ending EDT does not affect the result):
var dateAsDateObject = new Date(Date.parse(dateInRFC822Format));
This will work with dateInRFC822Format equal to either "Thu Sep 08 2011 12:00:00 GMT-0400 (EDT)" or "Thu Sep 08 2011 12:00:00 GMT-0400"
Now you can get the info you require from dateAsDateObject:
year: dateAsDateObject.getFullYear()
month: dateAsDateObject.getMonth()
day: dateAsDateObject.getDay()
Note: for formatting, if you don't mind using jqueryui you could also use the $.datepicker.formatDate() method. E.g. var stringRepresentation = $.datepicker.formatDate('yy-mm-dd', dateAsDateObject);
Try:
var mydate = new Date(originaldate);
mydate = mydate.getYear() + '-' + (mydate.getMonth() + 1) + '-' + mydate.getDate();

Categories