Convert Javascript current date time to UTC date time in milliseconds - javascript

I can't see a way to convert the current date/time in Javascript to a full date time in UTC. I need an equivalent to
var now = new Date().getTime();
but one that returns the UTC time in milliseconds
some thing like this
var UTCnow = new Date().getUTCTime();
I can't seem to see what I can use to make this happen in the JS Date object.
Any help would be appreciated.

Per the documentation:
The getTime() method returns the numeric value corresponding to the time for the specified date according to universal time.
getTime() always uses UTC for time representation. For example, a client browser in one timezone, getTime() will be the same as a client browser in any other timezone.
In other words, it already does what you are asking.
You can also do the same thing without instantiating a Date object:
var utcnow = Date.now();
Which the docs describe as:
The Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.

Related

Does Date.now() return different value for different timezones?

The definition for Date.now() is not clear for me. As per definition "The Date. now() is an inbuilt function in JavaScript which returns the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC.". So, does it mean that it will give same value for Date.now() in all timezone?
The current date and time, picked for calculation, is my local timezone or UTC ?
I have same query for java.util.Date getTime() method.
Yes, Date.now() will give you the same UTC timestamp independent of your current timezone. Such a timestamp, rather a point in time, does not depend on timezones.
The Java equivalent new Date() gives you the exact same thing.
Check out Coordinated Universal Time (UTC) for more information.
FYI: Don't use new Date() in Java as it's a legacy class. Use Instant.now() that is from the new java.time API that is much more robust and has a nicer design.

In javascript, how to get timezone value in UTC format for new Date(2017,05,31).toISOString()?

How to get timezone value for new Date(2017,05,31).toISOString()? It always comes as 000Z for any Date when the date is passed to the Date constructor. But for new Date().toISOString(), it gives the the timezone value.
new Date(2017,05,31).toISOString() gives "2017-05-30T18:30:00.000Z"
and new Date().toISOString() gives "2017-06-07T15:29:23.692Z". How to get timezone in UTC format for the past dates?
If you want the time to default to midnight in UTC, you can use Date.UTC(year, month, ...) to first create a timestamp based in UTC.
var utcMay31 = Date.UTC(2017, 4, 31); // note: 4 = May (0 = January)
Then, create the Date from that timestamp.
new Date(utcMay31).toUTCString(); // "Wed, 31 May 2017 00:00:00 GMT"
However, if you're wanting to know the timezone stored in the Date object, it doesn't actually have that. Dates represent an "instant" in time as the total number of milliseconds that have passed since Jan 1, 1970 00:00:00.000 UTC.
new Date().getTime(); // 1496851...
A Date can tell you the user's local offset from UTC in minutes at that instant.
new Date().getTimezoneOffset(); // e.g. 0, -480, 300
Otherwise, the timezone is limited to two choices when creating date strings, and the choice is based on the method used – user's local timezone or UTC.
new Date().toString(); // "now" in user's local time
new Date().toUTCString(); // "now" in UTC time
new Date().toISOString(); // "now" also in UTC time, alternate format
// etc.
You're confused ISO date values do not show the "time zone" instead they show the UTC time. Z stand for Zulu (UTC time).
2017-06-07T15:29:23.692Z
The bold part is not the time zone. It is the milli-seconds, the full time is in UTC. The reason it shows a 000Z in the set Date is because you didnt' set the milli-seconds.
If you want to display the time zone use toUTCString(). However it will display GMT which is UTC/Greenwich Time. To display the local time zone in a the date format you can use date.toLocaleString('en-US',{timeZoneName:'short'}) for example will display the date plus the local US time zone. Or you can use toString() which will display the GMT offset + the long local time zone.
In javascript, parsing, rendering and constructing dates will always assume local. It will convert to a timestamp, the number of milliseconds since 1-1-1970 00:00:00. JSON.stringify will convert to a UTC string, but legacy framworks use local dates. Always beware of this.
var myDate = new Date(); // this is now.
you can get your timezoneoffset (in minutes) with myDate.getTimezoneOffset(), but this will return the same offset for every date (aside from daylight saving time)
You shouldn't do this:
var utcDate = new Date(+d+60000*d.getTimezoneOffset());
// +d convert the date to a timespan.
// getTimezoneOffset() is in minutes
// *60000 makes that in milliseconds, the scale timespans operate upon
Date has a few methods to format dates, but always as local or UTC date. You need to do it manually if you want different time zones.
Note: the Date.UTC(...) function returns a timestamp. You sometimes see shifted dates, so they behave like UTC. But this causes problems later on.
var date = new Date(2000,1,1,12,0,0);
// DO NOT USE (breaks at start of daylight saving time)
// these are date/times that have the UTC-value,
// but Javascript treats them like local dates with this value.
utcDate1 = (+date-60000*d.getTimeZoneOffset()); // minus!!
utcDate2 = new Date(Date.UTC(2000,1,1,12,0,0));
// DO NOT USE (breaks at start of daylight saving time)
BTW
Edge, Chrome and Firefox display dates differently in the console: Edge and Firefox always shows local date, Chrome shows UTC. Also, if you change your timezone, Edge will screw up.

Want to get Timezone using jquery

In jquery,
var date = new Date();
It is taking system Date Not site Time zone
var date = (new Date()).getTimezoneOffset();
it is also not working.please anyone help for this.thank you.
Return the timezone difference between UTC and Local Time:
var d = new Date()
var n = d.getTimezoneOffset();
The result n will be:
-300
The getTimezoneOffset() method returns the time difference between UTC time and local time, in minutes.
For example, If your time zone is GMT+2, -120 will be returned.
Note: The returned value is not a constant, because of the practice of using Daylight Saving Time.
Tip: The Universal Coordinated Time (UTC) is the time set by the World Time Standard.
Note: UTC time is the same as GMT time.
jQuery has only one date/time function, which is $.now()
If you meant JavaScript, the answer is still no. You can only obtain a time zone offset from date.getTimezoneOffset(). You can't get a time zone - at least not in all browsers.
You can guess at the time zone, by using the jsTimeZoneDetect library, but it is just a guess. It may or may not be accurate.
If you can guarantee your users are running a browser that supports the brand new ECMAScript Internationalization API, you can get the user's time zone with:
Intl.DateTimeFormat().resolvedOptions().timeZone

How do you check whether a date is UTC in Javascript?

I've read this question:
How do you convert a JavaScript date to UTC?
and based on this I implemented this conversion in a dateTools module as follows:
[Update]
var dt, utcTime;
dt = new Date();
utcTime = new Date(Date.UTC(dt.getFullYear(),
dt.getMonth(),
dt.getDate(),
dt.getHours(),
dt.getMinutes(),
dt.getSeconds(),
dt.getMilliseconds()));
Now I'd like to write unit tests. My idea was to check whether the result is actually in UTC, but I don't know how.
All the toString, toUTCString and similar methods seem to be identical for the input (non UTC) and output (UTC) date.
Only the result of the getTime method differs.
Is there a way to check wheter a date is UTC in javascript? If not, is there a better idea to unit test this?
To give more context:
Only converting the it to a UTC string is not that helpful, because in the next step the date is sent to an Asp.net service and therefore converted to a string like:
'/Date([time])/'
with this code
var aspDate = '/Date(' + date.getTime() + ')/';
var aspDate = '/Date(' + date.getTime() + ')/';
This outputs the internal UNIX epoch value (UTC), which represents a timestamp. You can use the various toString methods to get a more verbose string representation of that timestamp:
.toString() uses the users timezone, result is something like "Fri Jan 25 2013 15:20:14 GMT+0100" (for me, at least, you might live in a different timezone)
.toUTCString() uses UTC, and the result will look like "Fri, 25 Jan 2013 14:20:15 GMT"
.toISOString() uses UTC, and formats the datestring according to ISO: "2013-01-25T14:20:20.061Z"
So how do we construct the time value that we want?
new Date() or Date.now() result in the current datetime. No matter what the user's timezone is, the timestamp is just the current moment.
new Date(year, month, …) uses the users timezone for constructing a timestamp from the single values. If you expect this to be the same across your user community, you are screwed. Even when not using time values but only dates it can lead to odd off-by-one errors.
You can use the setYear, setMonth, … and getYear, getMonth … methods to set/get single values on existing dates according to the users timezone. This is appropriate for input from/output to the user.
getTimezoneOffset() allows you to query the timezone that will be used for all these
new Date(timestring) and Date.parse cannot be trusted. If you feed them a string without explicit timezone denotation, the UA can act random. And if you want to feed a string with a proper format, you will be able to find a browser that does not accept it (old IEs, especially).
Date.UTC(year, month, …) allows you to construct a timestamp from values in the UTC timezone. This comes in handy for input/output of UTC strings.
Every get/set method has a UTC equivalent which you can also use for these things.
You can see now that your approach to get the user-timezone values and use them as if they were in UTC must be flawed. It means either dt or utcTime has the wrong value, although using the wrong output method may let it appear correct.
getTimezoneOffset
Syntax: object.getTimezoneOffset( ) This method
returns the difference in minutes between local time and Greenwich
Mean Time. This value is not a constant, as you might think, because
of the practice of using Daylight Saving Time.
i.e.
var myDate = new Date;
var myUTCDate = new Date(myDate - myDate.getTimezoneOffset() * 60000);
alert(myUTCDate);
note: 60000 is the number of milliseconds in a minute;

How to get current date and time in websql?

I wanted to know how to get current date and time and what datatype should i use to store it in websql, sorry for being such a noob...
You could create a Date object and store the numeric value of the date as the number of milliseconds since January 1, 1970, 00:00:00 UTC (negative for prior times).
var today = new Date();
today.getTime(); // returns "1337217238392"
Storing the milliseconds will allow you to read and parse however you like later. Its worth mentioning to check out date.js and moment.js

Categories

Resources