parameter for javascript Date object is different from documentation? - javascript

I read in the documentation it says that for Date object, the month parameter is zero-based. but somehow my code doesn't return the month as zero-based.. is it because my computer's settings? will it affect other users when browsing my website?
I'm trying to get a Date object for the previous month.
what I tried:
var mydate = new Date(2017, 11, 1); // result: Date 2017-11-30T17:00:00.000Z
var mydate = new Date(2017, 12, 1); // result: Date 2017-12-31T17:00:00.000Z
var mydate = new Date(2018, 0, 1); // result: Date 2017-12-31T17:00:00.000Z

From the docs in the Note section of parameters -
Note: Where Date is called as a constructor with more than one argument, the specified arguments represent local time. If UTC is desired, use new Date(Date.UTC(...)) with the same arguments.
var mydate = new Date(Date.UTC(2017, 11, 1));
console.log(mydate);
var mydate = new Date(Date.UTC(2017, 12, 1));
console.log(mydate);
var mydate = new Date(Date.UTC(2018, 0, 1));
console.log(mydate);
P.S why output for second is as 2018-01-01 is coz
Note: Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0, 70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a date for 2013-03-01T01:10:00.

The issue you are facing is not because of how the date is being returned it is due to the fact that your local time is ahead of UTC (by 7 hours), this causes the returned date (which is in UTC) to show as the previous day at 5pm [17:00:00.000Z]
(when you don't specify a time it saves the time as 00:00:00.000Z) a solution to your problem would be to convert all times to a single timezone. It should not have any effect on users visiting your website if you use the same timezone for all your values.

Related

Get the number of hours between the given dates using date-fns library

My api provides me with a "datePublished: "2019-11-14T14:54:00.0000000Z" timestamp. I want to subtract this from the current time, date.now() or new Date() and get the difference in hours. I am using the date-fns v2 library
From the date-fns docs
var result = differenceInHours(
new Date(2014, 6, 2, 19, 0),
new Date(2014, 6, 2, 6, 50)
)
I am trying this:
var result = differenceInHours(
2019-11-14T14:54:00.0000000Z,
new Date()
)
console.log(result) = NAN
When I use the datePublished value and the current date, I get NAN. Do I have to format the API date into a different format?
https://date-fns.org/v2.7.0/docs/differenceInHours
That's because you are comparing string with Date and not Date with Date.
Check this:
var result = differenceInHours(
new Date('2019-11-14T14:54:00.0000000Z'),
new Date()
)

How to check invalid date in Javascript in FireFox

I want to test invalid date, the function I wrote works fine in chrome but not in Firefox. Here are some examples not working in FF:
new Date('01/99/2010') = return Valid Date
new Date('99/01/2010') = return Valid Date
var day='01', month = '99', year = '2010';
new Date(year,month,day) = return Valid Date
var day='99', month = '01', year = '2010';
new Date(year,month,day) = return Valid Date
Above methods return "Invalid Date" in Chrome, but not in Firefox. Does anyone know the proper way to validate date in Firefox.
PS: Input string could be - mm/dd/yyyy or dd/mm/yyyy or yyyy/mm/dd
It looks like Firefox takes this rule one step further than Chrome:
Note: Where Date is called as a constructor with more than one
argument, if values are greater than their logical range (e.g. 13 is
provided as the month value or 70 for the minute value), the adjacent
value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to
new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the
month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0,
70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a
date for 2013-03-01T01:10:00.
Source - MDN Date documentation.
The emphasis here is on with more than one argument. That's why Chrome does what Firefox does for:
new Date(2010, 99, 1); - a valid date object.
but because:
new Date('01/99/2010'); is technically only a single argument, it doesn't fall for the above rule in Chrome, but Firefox allows it through.
With the above in mind, and the inconsistency across browsers, it looks like you might be stuck writing a validator for the day, month and year separately from trying to do it via the Date object if you want it to work in Firefox.
You can use regex. Try this:
var rgx = /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/;
console.log(rgx.test("99/12/2015"));
jsFiddle
I would use a internal JavaScript funtion for validating Dates, as browsers do handle those data types very differently.
function isValidDate(date)
{
var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
if (matches == null) return false;
var d = matches[2];
var m = matches[1] - 1;
var y = matches[3];
var checkDate = new Date(y, m, d);
return checkDate.getDate() == d &&
checkDate.getMonth() == m &&
checkDate.getFullYear() == y;
}
You would then use it like this:
var d = new Date(2010, 99, 1);
console.log( isValidDate(d) ); // returns false no valid date

Why the dates 2014 Oct 31 and 2014 Nov 01 using date Object have same values in Javascript?

Why both dates in the below code have same valueOf() and getTime()?
<script>
var endDt = new Date(2014,10,31);
var endDt2 = new Date(2014,11,1);
alert("getTime()\nendDt : "+endDt.getTime()+"\nendDt2: "+endDt2.getTime());
alert("valueOf()\nendDt : "+endDt.valueOf()+"\nendDt2: "+endDt2.valueOf());
</script>
We can see that both values is equals.
I want to get the values to lock the user if user try a interval greater than 31 days.
But when the user puts start Date(2014,10,01) and end Date(2014,11,1) the javascript interprets as end Date(2014,10,31). When i do calc. with difference between start date and end date both values is the same.
<script>
var startDt = new Date(2014,10,01);
var endDt = new Date(2014,10,31);
var endDt2 = new Date(2014,11,1);
var diff = endDt.getTime()-startDt.getTime();
var diff2 = endDt2.getTime()-startDt.getTime();
alert("getTime()\ndiff: "+diff+"\ndiff2: "+diff2);
diff = endDt.valueOf()-startDt.valueOf();
diff2 = endDt2.valueOf()-startDt.valueOf();
alert("valueOf()\ndiff: "+diff+"\ndiff2: "+diff2);
</script>
Why are these values coming up the same, even though the provided dates are different?
You are creating the wrong dates. Months are 0-based in JavaScript, so new Date(2014,10,31); is (theoretically) Nov 31st and new Date(2014,11,1) is Dec 1st.
Of course Nov 31st doesn't exist, so it's correct to Dec 1st.
From the big yellow box in the MDN documentation:
Note: Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based).

Issue with converting string which is of DateTime to javascript Date

I have a string which contains DateTime as "20140121230000" . If i try to convert this into a Date.
var oDate = new Date(20140121230000);
i'm getting the year as 2068! Is there a way to convert this into a Date which is of year 2014, month 01 Date 21 Time 23:00:00 ?
Is it possible to directly convert this without doing any parsing in the string ?
Unless you use a library there is no way to convert the value without manually splitting the string.
var year = +oDate.slice( 0, 4);
var month = +oDate.slice( 4, 2) - 1; // Month is zero-based.
var day = +oDate.slice( 6, 2);
var hour = +oDate.slice( 8, 2);
var minute = +oDate.slice(10, 2);
var second = +oDate.slice(12, 2);
// This will interpret the date as local time date.
var date = new Date(year, month, day, hour, minute, second);
// This will interpret the date as UTC date.
var utcDate = Date.UTC(year, month, day, hour, minute, second);
The constructor you used takes millisecond since 1st Jan, 1970, try using :
var oDate = new Date(2014, 01, 21, 23, 00, 00, 00);
Note, month 01 will be Feb, not Jan.
Constructing a Date object with a string
new Date(string)
expects a date string that Date.parse can understand:
ISO 8601 (e.g. 2011-10-10T14:48:00), or
RFC2822 (e.g., Mon, 25 Dec 1995 13:30:00 GMT)
See MDN for more information on Date and Date.parse.
Yours is not a recognized format. You can either
reformat the string to fit one of the formats above
split the string manually and call Date with individual parameters, as in new Date(year, month, day, hour, minute, second, millisecond)
use a library like moment.js
Using moment.js would look something like this:
moment("20140121230000", "YYYYDDMMHHmmss")
See moment.js string + format for more information about the format syntax.
Given '20140121230000', you can split it into bits and give it to the Date constructor:
function parseSToDate(s) {
var b = s.match(/\d\d/g) || [];
return new Date( (b[0] + b[1]), --b[2], b[3], b[4], b[5], b[6]);
}
console.log(parseSToDate('20140121230000'));

Epoch time .NET to JavaScript (hour off?)

Using the following code in .NET
Input: "2011-09-14 00:00:00.0000000" (From an SQL datebase loaded into a Date datetype becoming #9/14/2011#)
<Extension()>
Public Function ToEpoch(value As Date) As Double
Dim span As TimeSpan = (value - New Date(1970, 1, 1, 0, 0, 0, 0).ToLocalTime)
Return span.TotalMilliseconds
End Function
And this in JavaScript
var StartDate = new Date(<%= StartDate() %>);
Resulting in this output
var StartDate = new Date(1315922400000);
It appears that only for this specific input the StartDate (on the javascript side) is exactly one hour off.
Resulting in the JavaScript datetime of: Tue Sep 13 23:00:00 UTC+1000 2011
If I input a value like Date.Now it appears to function correctly.
I assume I'm missing something fundamental?
Seems to me that unix epoch is Jan 1, 1970, UTC.
In light of that, your creation of the Date and then conversion to local time is somewhat backwards. What you need to do is convert the variable time value to UTC.
<Extension()>
Public Function ToEpoch(value As Date) As Double
Dim span As TimeSpan = (value.ToUniversalTime -
New System.DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
Return span.TotalMilliseconds
End Function
You may think the two conversions are equivalent, but they may not be, as explained in
http://blogs.msdn.com/b/oldnewthing/archive/2003/10/24/55413.aspx .
I suspect the two dates have different daylight savings values. See if the following calls to IsDaylightSavingTime() return the same values:
Dim dt As Date = new Date(2011, 9, 14)
Dim epoch As Date = new Date(1970, 1, 1)
dt.IsDaylightSavingTime()
epoch.IsDaylightSavingTime()

Categories

Resources