Epoch time .NET to JavaScript (hour off?) - javascript

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()

Related

parameter for javascript Date object is different from documentation?

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.

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'));

Javascript date format using string month

All the other topics on date format assume that dates are entered as integers.
I'm writing a script (Linux) that requires the month to be a string (Jan, Feb, Mar etc) and need to validate the dates.
I've written a clunky routine that extracts the month, determines the month number and then does the comparison but I was hoping there might be something neater out there to do this? I thought I had seen something about using a 'format' method but I can't find it now...
I've tried this but it fails miserably:
var checkDate1 = document.getElementById('fromDate').value;
var checkDate2 = document.getElementById('toDate').value;
tmpDate1 = new Date(checkDate1);
tmpDate2 = new Date(checkDate2);
if (tmpDate1 < tmpDate2) {
where a typical field entry will be '12-may-2012', for example.
NOTE: I don't have access to add any fancy, whizzy libraries to the system so have to make do with the vanilla stuff.
In JavaScript, to be parsed in the constructor, string Date must have the format : D, d M Y H:i:s
Now it'll be : Tue, 29 May 2012 15:22:59
If you want to stay with string, you'll have to make a fancy function that parse your value, and find what day will be the 29 May of 2012.
Another method ( and easier ) is to create a new Date, parse you value and use the on of the other constructors
var today = '05-29-2012',
aToday = today.split('-'),
dToday = new Date(aToday[2], aToday[0], aToday[1], 0, 0, 0, 0),
tomorrow = '05-30-2012',
aTomorrow = tomorrow.split('-'),
dTomorrow = new Date(aTomorrow[2], aTomorrow[0], aTomorrow[1], 0, 0, 0, 0);
if (dTomorrow.getTime() > dToday.getTime() ) {
console.log('Tomorrow is tomorrow');
} else {
console.log('Tomorrow is not tomorrow');
}

What is the analogue of Date.UTC in .NET

Java script has Date.UTC method which is used like that Date.UTC(2004,3,1) is there the same in .NET?
I was trying to use DateTime.ToFileTimeUtc() but it is returning differs value.
For example if i have this date
javascript Date.UTC(2004,3,1) will return this 1075766400000
but DateTime.ToFileTimeUtc() will return this 127175616000000000
Need help
UPDATE
when i am using this
TimeSpan timeSpan = new DateTime(2004, 3, 1, 0, 0, 0, DateTimeKind.Utc) - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long milliSeconds = (long)timeSpan.TotalMilliseconds; // equal to 1073088000000
the milliSeconds equal to 1073088000000 but in case of Date.UTC(2004,3,1) it is 1075766400000 http://jsfiddle.net/M3aJQ/
the difference is 00:04:27.8400000
As #Jon Marting says;
DateTime Constructor (Int32, Int32, Int32, Int32, Int32, Int32, DateTimeKind)
and use DateTimeKind.Utc
public DateTime(
int year,
int month,
int day,
int hour,
int minute,
int second,
DateTimeKind kind
)
The DateTime method ToUniversalTime() will convert to UTC correctly.
DateTime now = DateTime.Now;
DateTime utc = now.ToUniversalTime();
of course for .Now in UTC you can also use:
DateTime utcnow = DateTime.UtcNow;
DateTime.ToFileTimeUtc() uses a different epoch to Date.UTC() in JavaScript. That's why you get different answers. According to MSDN it returns the "number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC)".
Whereas, I believe JavaScript's Date.UTC method returns the number of milliseconds since midnight of January 1, 1970.
You could do it yourself, something like this in .net:
TimeSpan timeSpan = new DateTime(2004, 3, 6, 0, 0, 0, DateTimeKind.Utc) - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long milliSeconds = (long)timeSpan.TotalMilliseconds;

Categories

Resources