I am using JSON.Stringfy() to convert my date to String format. but the date so returns is the UTC time for my system.
here is the code.
var dateFrom;
dateFrom=new Date(); // outputs--> Wed Sep 24 2014 16:03:22 GMT+0530 (India Standard Time)
dateFrom=JSON.stringify(x); //outputs--> "2014-09-24T10:33:22.135Z"
//Expected result--> "2014-09-24T16:03:22.135Z"
I think there is something which convert my current date to UTC date. is there any way to get the expected result..any comments would be valuable..
thanks in advance
JSON follows a common format while it converts date objects into strings. Dates are encoded as ISO 8601 strings and then treated as strings while they get serialized.
But it doesnt mean that your date object got modified. It just got represented in a different format which enforced by JSON. So the date still points to the same timestamp which you refer via IST.
So your statement that it alters the date is wrong, it just alters the representation format.
var d = new Date();
//shows local format
alert(d);
djson=JSON.stringify({"date":d});
//shows UTC format
alert(djson);
dobj=JSON.parse(djson);
//again UTC format
alert(dobj.date);
d = new Date(dobj.date);
//again local format
alert(d);
Related
The codes below return current UTC datetime in string format.
But i am looking for a function in javascript that return current utc datetime in datetime format.
It seems there is no such that function in javascript.
var dateTime_now = new Date();
var dateTime_now_utc_str = dateTime_now.toUTCString();
alert(dateTime_now_utc_str);
.toISOString() is what you want, not .toUTCString()
You already have the Javascript internal DateTime format in the variable dateTime_now. So I think you do want a string output, but not the string Sun, 05 Dec 2021 06:11:15 GMT, because it contains useless strings like Sun and useful, but non-numerical strings like Dec. I am guessing you do want a string output, but containing digits and separators and no words.
var dateTime_now = new Date();
var dateTime_now_utc_str = dateTime_now.toISOString();
console.log(dateTime_now_utc_str);
// Result: 2021-12-05T06:10:54.299Z
Why?
A detailed explanation of why is given here, by me:
https://stackoverflow.com/a/58347604/7549483
In short, UTC simply means "in the timezone of GMT+0", while ISO is the name of the format yyyy-mm-dd etc. The full name of the date format is ISO 8601.
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();
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.
I'm using the following code to get current date and time in nodejs.
var date = (new Date()).toJSON();
after converting to JSON, it returns a wrong time with a wrong timezone as below:
2018-01-03T11:16:38.773Z
but without toJSON() it returns the real time in correct timezone
Wed Jan 03 2018 14:47:12 GMT+0330 (Iran Standard Time)
The format is different because:
The toJSON method is a built-in member of the Date JavaScript object.
It returns an ISO-formatted date string for the UTC time zone (denoted
by the suffix Z).
What you can do:
You can override the toJSON method for the Date type, or define a
toJSON method for other object types to achieve transformation of data
for the specific object type before JSON serialization.
source
If you want the same result you could just use toString instead of toJSON:
var date = new Date().toString();
2018-01-03T11:17:12.000Z === Wed Jan 03 2018 14:47:12 GMT+0330 (Iran Standard Time)
The one on the left hand side is ISO timezone and one on the right is basically the browser timezone.
(new Date()).toJSON() converts into ISO timezone
So a simple way to convert to string is
var date = (new Date()).toString();
This works perfectly fine on the client-side, at first:
var timeOfMessageSent = new Date();
console.log(timeOfMessageSent); // Mon May 22 2017 14:03:13 GMT+0200 (Romance Summer Time)
var day = timeOfMessageSent.getDay(); // 1
console.log("this is the day: ",day);
However, after having sent the date to the server, and then sent it back to the client, it doesn't work.
Now the date is displayed like this: 2017-05-22T12:03:13.437Z
I guess that's why getDate doesn't work.
How do I make sure that the date is displayed like at first? e.g. 2017-05-22T12:03:13.437Z
Make your server date string to date object.
var timeOfMessageSent = new Date();
console.log(timeOfMessageSent); // Mon May 22 2017 14:03:13 GMT+0200 (Romance Summer Time)
var day = timeOfMessageSent.getDay(); // 1
console.log("this is the day: ",day);
var newDate = new Date("2017-05-25T12:19:55.982Z"); // give your server date and return as date object
var newDay = newDate.getDay();
console.log("this is the new day: ", newDay);
It seems the date gets returned by the server as an ISO string. You have to create a new Date instance from this string.
Using strings to create date objects are usually discouraged, but an ISO date string is standard and the safest date string format to initialize a date object from.
A Javascript date object is not something that can be part of JSON, so it needs to be converted to a string or a number in order to be transmitted through a JSON API. That's why the server returns this ISO string representation of the date.
An alternative to ISO string commonly used by JSON APIs is to convert the date to a number representing the milliseconds of the date. Both varieties can be converted back to a Javascript date object with the date constructor: new Date(dateValue)
The ISO string you get back can be modified to your preference using moment.js. With that library you can show the date however you want.