Parsing into UTC/GMT time with date-functions.js library - javascript

Doing this with the date-functions.js library (used e.g. in datetimepicker jQuery plugin):
Date.parseDate('2018-03-10 12:12', 'Y-m-d H:i')
gives:
Sat Mar 10 2018 12:12:00 GMT+0100 (Paris, Madrid)
How to get the result as Unix timestamp or GMT / UTC time instead?

A string like '2018-03-10 12:12' will usually be parsed as local as there is no timezone offset. It's also not ISO 8601 compliant so using the built-in parser will yield different results in different browsers.
While you can use a library, to parse it as UTC and get the time value is just 2 lines of code:
function toUTCTimeValue(s) {
var b = s.split(/\D/);
return Date.UTC(b[0],b[1]-1,b[2],b[3],b[4]);
}
// As time value
console.log(toUTCTimeValue('2018-03-10 12:12'));
// Convert to Date object and print as timestamp
console.log(new Date(toUTCTimeValue('2018-03-10 12:12')).toISOString());

var date = new Date('2018-03-10 12:12'.replace(' ', 'T'));
// Unix
console.log(Math.floor(date.getTime() / 1000));
// UTC
console.log(date.toUTCString());
As always, please have a look at the documentation at MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Use MomentJS instead. You can specify exactly what format the string you're parsing is in. MomentJS can then provide you with the underlying Date object, unix timestamp as well as convert to UTC.
var d = moment('2018-03-10 12:12', 'YYYY-MM-DD HH:mm');
console.log(d.toDate());
console.log(d.unix());
console.log(d.utc().toDate());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>
You could of course also parse the date as UTC too instead of treating it as a local time.
moment.utc('2018-03-10 12:12', 'YYYY-MM-DD HH:mm');
NOTE Bit difficult for me to test UTC as I'm in the UK and GMT and UTC are virtually the same.

Related

Get Date Object with UTC instead of local time zone in vanilla javascript

I am uploading a date time to a field on a dynamics form, and the form needs to receive a UTC date time. If I do something like this:
new Date(new Date().toISOString())
If i console.log the date it shows as: Fri Dec 18 2020 14:27:39 GMT-0500 (Eastern Standard Time)
I want the object to print as the UTC time with UTC specified as the time zone, otherwise the form (expecting a date object) keeps uploading as the EST time.
Use Date.UTC
const utcDate1 = new Date(Date.UTC(96, 1, 2, 3, 4, 5));
Docs
Edit: As another user mentioned, you must use Date.UTC.
var date = new Date(Date())
var utcDate = date.toUTCString();
console.log(utcDate)
Date objects are just an offset in milliseconds from the ECMAScript epoch, 1970-01-01T00:00:00Z. They do not have a timezone. When you stringify the object you get a timestamp that depends on the method used.
Most methods (e.g. toString) use the host settings for timezone and offset and produce timestamps based on those settings.
If you want an ISO 8601 compliant string with zero offset, the use toISOString or toUTCString depending on the format you want:
let d = new Date();
console.log(`local time : ${d.toString()}`);
console.log(`toISOString: ${d.toISOString()}`);
console.log(`toUTCString: ${d.toUTCString()}`);
See How to format a JavaScript date.
In your code, the expression:
new Date(new Date().toISOString())
firstly creates a Date object for the current moment in time, then generates a timestamp per the toISOString method. That is then parsed back into a Date object, so the result is identical to:
new Date();

How to convert GMT time to user's Local time Javascript

I'm trying to convert a GMT time to the user's Local time.
the format of the time i'm getting from the server is : 2015-05-20 18:00:00 GMT
I just want to show hours and minutes like that : 20:00
I wanted to use this solution which seems pretty easy, but I don't know how to make my format same as this
var date = new Date('5/21/2015 18:52:48');
date.toString();
the format of the time i'm getting from the server is : 2015-05-20 18:00:00 GMT
If so, you can easily massage that into a format that ES5 and higher browsers are supposed to support, which would be 2015-05-20T18:00:00Z for your example:
var yourString = "2015-05-20 18:00:00";
var dt = new Date(yourString.replace(' ', 'T') + "Z");
var hours = dt.getHours(); // Will be local time
var minutes = dt.getMinutes(); // Will be local time
Then just format the hours and minutes values you get into your desired hh:mm string.
Note: The Z at the end of the string is important. Unfortunately, the ES5 specification has a significant error in it (they're fixing it in ES6) around what the engine should do if there is no timezone on the string being parsed. Some engines do what the spec says, others do what the spec should have said (and the ES6 spec will say), which unfortunately means that right now, you can't trust what browsers will do if there's no timezone on the string.
I just had to add " UTC "
var date = new Date('2015-05-20 15:00:00 UTC');
alert(date.getHours());
alert(date.getMinutes());
new Date() in browser returns date object in user's timezone(machine timezone).
Just you need to pass GMT date to Date function in ISO format. So it will treat it as gmt time.
var date = new Date('2015-05-21T18:52:48Z');
date.toString();//You will get here date string in local format
You can also use UTC as UTC and GMT are same.
Here is ex.
var date = new Date('2015-05-21 18:52:48UTC'); //You can use GMT instead UTC
date.toString();//You will get here date string in local format
First method is preferable as second method doesn't work on Internet Explorer

Converting a String Date to a Unix Timestamp in Javascript

How can I parse a date such as the following and convert it to a Unix timestamp using JavaScript?
Sat Mar 29 2014 16:10:00 GMT+0800 (Taipei Standard Time)
Thanks.
you just need a good date-parsing function, I would look at date.js . It will take just about any date string you can throw at it, and return you a JavaScript Date object.
Once you have a Date object, you can call its getTime()
method, which will give you milliseconds since January 1, 1970. Just divide that result by 1000 to get the unix
timestamp value.
In code, just include date.js, then:
var unixtime = Date.parse("24-Nov-2009 17:57:35")
.getTime()/1000
Get date.js from http://www.datejs.com/
More here: https://stackoverflow.com/a/1792009/390897

JS get date in UTC time

I've created a date in JS like so:
var myDate = new Date('2013-01-01 00:00:00');
I assume JS reads this in as UTC time. But when I do something like myDate.getTime() the timestamp returned was something like 4AM GMT time.
Why is this? And how do I get the date as midnight in UTC time?
At least in Chrome, this works:
var myDate = new Date('2013-01-01 00:00:00 UTC');
It also works if you put GMT instead of UTC. But I don't know if this is cross-browser enough.
I live in India. Hence my timezone is the Indian Standard Time (IST) which is listed in the tz database as Asia/Kolkata. India is 5 hours 30 minutes ahead of GMT. Hence when I execute new Date("2013-01-01 00:00:00") the actual time at GMT is "2012-12-31 18:30:00".
I believe you live in America because you're in the EST timezone (GMT-04:00)? Am I right?
If you want to parse the time at GMT instead of your local timezone then do this:
new Date("2013-01-01T00:00:00+00:00");
Notice the capital T between the date and the time, and the +00:00 at the end. This is the format used to parse a given time in a specific timezone.
Given the date string "2013-01-01 00:00:00" you can convert it to the required format using the following function:
function formatDateString(string, timezone) {
return string.replace(" ", "T") + timezone;
}
Then you can create the date as follows:
new Date(formatDateString("2013-01-01 00:00:00", "+00:00"));
Another way to convert local time to GMT is as follows:
var timezone = new Date("1970-01-01 00:00:00"); // this is the start of unix time
Now that you have your own local timezone as a date object you can do:
new Date(new Date("2013-01-01 00:00:00") - timezone);
All the above methods produce the same date at GMT.
JS reads this with time zone that your computer uses.
You can try use myDate.toUTCString() for get date in UTC time.
If you want get timestamp use myDate.getTime()
Mine works simply by doing this
var datetime= new Date()
However the month is 1 low so you have to add one

What string date format will JavaScript's parse recognize?

I know when constructing a Date object in JavaScript with a dateString parameter, the string must be something that parse() can recognize.
What date format can parse recognize?
For example:
var postDate = new Date("2011-03-08T23:52:38");
works in Chrome and Internet Explorer, but fails on an iPhone (returns Jan 1, 1970).
I cannot find any formal documentation on the .parse() method, or the constructor, about what the parameter should be.
The format yyyy-mm-ddThh:nn:ss doesn't work. What is the allowed format string?
The MDC documentation of Date.parse() states (quoting) :
It accepts the IETF standard (RFC
1123 Section 5.2.14 and elsewhere)
date syntax: "Mon, 25 Dec 1995 13:30:00 GMT".
OP Edit:
.NET syntax to create this datetime string:
/*
* r (RFC1123Pattern)
* ddd, dd MMM yyyy HH':'mm':'ss 'GMT'
* Mon, 15 Jun 2009 20:45:30 GMT
*/
dateTime.ToUniversalTime().ToString("r", CultureInfo.InvariantCulture); //"r" = RFC1123Pattern
Edit: The r (RFC1123 pattern) always appends "GMT", even though the time isn't GMT (it's local). You need to call .ToUniversalTime() first, in order to have the time actually be GMT.
Using the format that is produced by Date's toJSON method will work. This is the same as the toISOString method.
The date format is YYYY-MM-DDTHH:mm:ss.sssZ
Note: The time zone is always UTC as denoted by the suffix "Z".
var d = new Date();
console.log(d.toJSON());
console.log(d.toJSON() === d.toISOString());
console.log(Date.parse(d.toJSON()) === Date.parse(d.toISOString()));
You may find that the date shown isn't the same as on your clock; remember the time zone is UTC.
References:
Date.prototype.toJSON()
Date.prototype.toISOString()

Categories

Resources