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.
Related
I'm working on a project right now where I want to get an array of dates between two end points. I've got that code working perfectly when I hard code the start and end date in.
My problem is when I used an input, the code doesn't work. How can I convert a normal date input into a UTC string?
Here's an example of what I'm on about: https://jsfiddle.net/mksvh95y/5/
<input type="date" id="bubbles" placeholder = "enter date">
<button onclick="getDate()"> Click me to get date</button>
<script>
function getDate(){
var water = document.getElementById("bubbles").value;
alert(water);
//alert(water.toUTCString());
var fire = new Date (2018,10,15);
alert(fire);
}
I want the get the 'water' variable to be formatted like the 'fire' variable.
I saw there's .toUTCstring(), but that doesn't work
This is possibly a duplicate of Why does Date.parse give incorrect results, but here's an answer that may be more suitable.
The value of a date input is an ISO 8601 format date string in the format "YYYY-MM-DD", which is what you should see from:
alert(water); // something like 2018-06-21
The format of the string returned by Date.prototype.toString is implementation dependent (though ECMAScript 2019 will standardise it). That's the format you're getting from:
alert(fire) // e.g. Thu Jun 21 2018 00:00:00 GMT+1000 (AEST)
One fix is to convert the string from the date input to a Date, then use the default toString for both outputs. But your problem then is that parsing of the ISO 8601 date string is UTC, so the dates will be different by the host timezone offset, e.g.
console.log(new Date('2018-06-21').toString()); // 21 Jun 2018
console.log(new Date(2018, 5, 21).toString()); // 21 Jun 2018
So you need to parse the string from the input as local using a simple function like:
function parseISOLocal(s) {
var b = s.split(/\D/);
return new Date(b[0],b[1]-1,b[2]);
}
console.log(parseISOLocal('2018-06-21').toString());
console.log(new Date(2018, 5, 21).toString());
If you want to use a library like moment.js, it will parse ISO 8601 formatted date strings as local (which is consistent with ISO 8601), then convert it to a plain Date and use the default toString, e.g.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<input type="date"
onchange="console.log(moment(this.value).toDate().toString())">
I strongly recommend using the excellent MomentJS library for date mainpulation, as native support is poor:
function getDate(){
var water = document.getElementById("bubbles").value;
var waterMoment = moment(water);
alert(water.utc().format()); //outputs a UTC date string
var fire = new Date (2018,10,15);
alert(fire);
}
See the moment.utc() function and the moment.format() function for more details.
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.
I have date string like yyyy-MM-dd HH:mm:ss.SSS which is PST timezone, I need to change it to UTC format 2016-07-28T17:22:51.916Z. How can I do that?
This can be done pretty easily in JS:
var pstDate = new Date(myValidPstDateString);
// ISO is always in UTC time
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
console.log(pstDate.toISOString());
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);
How does one convert a string of a date without a year to a JS Date object? And how does one convert a date string with a year and a time into a JS Date object?
Many different date formats can be converted to date objects just by passing them to the Date() constructor:
var date = new Date(datestring);
Your example date doesn't work for two reasons. First, it doesn't have a year. Second, there needs to be a space before "pm" (I'm not sure why).
// Wed May 27 2009 23:00:00 GMT-0700 (Pacific Daylight Time)
var date = new Date("2009/05/27 11:00 pm")
If the date formats you're receiving are consistent, you can fix them up this way:
var datestring = "05/27 11:00pm";
var date = new Date("2009/" + datestring.replace(/\B[ap]m/i, " $&"));
I'd use the Datejs library's parse method.
http://www.datejs.com/
I tried your example and it worked fine...
5/27 11:00pm
Wednesday, May 27, 2009 11:00:00 PM
I have used the Dojo time parser to do things like this:
Check it out:
http://api.dojotoolkit.org/jsdoc/HEAD/dojo.date.locale.parse
Not the cleanest, but works:
var strDate = '05/27 11:00pm';
var myDate = ConvertDate(strDate, '2009');
function ConvertDate(strWeirdDate, strYear)
{
strWeirdDate = strWeirdDate.replace(/ /, '/' + strYear + ' ');
return new Date(strWeirdDate);
}
Probably want to trim the string first as well.
Just another option, which I wrote:
DP_DateExtensions Library
It has a date/time parse method - pass in a mask and it'll validate the input and return a data object if they match.
Also supports date/time formatting, date math (add/subtract date parts), date compare, speciality date parsing, etc. It's liberally open sourced.