Using something like iso8601.js solves this varying behaviour by defining a single implementation of the Date object.īy default, the spec says you can create dates with an extended ISO 8601 date format like var someDate = new Date('T12:00Z')
#Javascript get utc time trial#
My biggest complaint about the Date object is the amount of undefined behaviour that browser implementers have chosen to include, which can confuse people who attack dates in js with trial and error than reading the spec. In js, all Date values have an underlying UTC value which is passed around and known regardless of the offest or time zone conversions that you do. The C# DateTime objects have a Kind property, but no strict underlying time zone as such, and time zone conversions are difficult to track if you are converting between two non UTC and non local times. I actually think Date values in js are far better than say the C# DateTime objects. This is because getUTCDate() returns the day of the month whereas, getUTCDay() returns the day of the week. "Sun, 03:50:34 GMT" // four hours less than my local time, and two hours less than the original time - because my GMT+2 input was interpreted as GMT+0!Īlso note that getUTCDate() cannot be substituted for getUTCDay(). > var d2 = new Date( d1.getUTCFullYear(), d1.getUTCMonth(), d1.getUTCDate(), d1.getUTCHours(), d1.getUTCMinutes(), d1.getUTCSeconds() ) "Sun, 05:50:34 GMT" // two hours less than my local time
Observe (I'm in GMT +02:00 right now, and it's 07:50): > var d1 = new Date() If UTC time is passed in, the results will differ. For a string representation, David Ellis' answer works. It will factor the current timezone offset into the result. Note that getTime() returns milliseconds, not plain seconds.įor a UTC/Unix timestamp, the following should suffice: Math.floor((new Date()).getTime() / 1000)
#Javascript get utc time android#
(I had problems getting that to work in an older Android browser.) To set the timezone of a certain date object is to construct it from a date string that includes the timezone. Dates constructed that way use the local timezone, making the constructed date incorrect.