Convert datetime string to UTC in JavaScript - javascript

How can we convert datetime string to UTC in javascript. We are getting following JSON from REST service
[
{
"CreationTime":"June 2, 2015 8:04:53 PM IST",
"category":"UI",
"severity":"MAJOR",
"source":"BILLING",
"status":"ASSIGNED"
}
]
we are able to get CreationTime into a String variable but unable to convert to UTC. Any idea to convert this?

Using toUTCString():
var toUTC = new Date("June 2, 2015 8:04:53").toUTCString()
In Javascript you can use this method to convert a date from a Date() object, but not from a IST string. So you need format this string to a Date() object , then you can convert it to UTC. In this topic says what I mean.
Note If you try June 2, 2015 8:04:53 PM IST JavasScript take it as invalid date, for that you have to use .replace() function to remove the IST part of the string.

Related

Javascript | Get Current UTC DateTime In DateTime Format - Not String

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.

Javascript input a UTC string

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.

Convert session.lastAccessedTime into javascript date object

I need to convert session.lastAccessedTime object from jsp into Javascript Date object. Currently, it displays as long object. How can I convert to Javascript date object?
console.log('MaxInactive Interval == ' + ${pageContext.session.lastAccessedTime});
You can use Date.parse() method to convert date string to date object.
MDN Date.parse()
The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC
Date.parse(lastAccessedTime)

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

sending javascript date to vb.net date variable

I need to pass javascript date value to vb.net function.
Method iam using now:
convert javascript date to string
store it in hiddenfield
retrieve string from hidden field in server code and parse it using date.parse
the trouble is that the Javascript dateformats
toString() - Sat Apr 4 22:19:00 UTC+0530 2009
toDateString() - Sat Apr 4 2009
toLocaleString() - Saturday, April 04, 2009 10:19:00 PM
doesnt match vb date format. I am getting error that its unparseable.
Thanks in advance for the help
The problem with using ToLocaleString is that you lose timezone info and its obviously locale specific which means you need to parse it with the right culture.
I was thinking:-
DateTime d = DateTime.ParseExact(sInput, "ddd MMM d HH:mm:ss UTCzzzz yyyy" , CultureInfo.InvariantCulture);
But that isn't cross browser compliant (the ECMA spec does not define what toString should actually do).
However we do know that the value of a Javascript Date object is the number of milliseconds from midnight Jan 1, 1970. Hence you could instead store the .valueOf of a date object in your hidden field. Use Int32.Parse on the string first, create a TimeSpan from the that value and add it to a DateTime of Jan 1, 1970 00:00:00 UTC+0000.
int milliseconds = Int32.Parse(inputString);
TimeSpan t = TimeSpan.FromMilliseconds(milliseconds);
DateTime base = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime result = base + t;
Why not instead pass the Javascript date as a string and then convert it to a date type in VB.net.
Public Function ConvertJavaScriptDate(ByVal d as String) As Date
Return Date.Parse(d)
End Function
Another option is to use CType(d,Date). CType is a lexical cast that will try a variety of ways to convert the string value to a Date.
I'm not terribly familiar with the difference between a JavaScript Date and a VB.Net Date in terms of format, but if you post an example I'm sure we can get a basic conversion going.
Since I don't have to worry about culture difference I am going to use toLocaleString().
toLocaleString() parses fine to a string compatible with Date.Parse().
Anyway thanks for posting your replies.
This just a datetime formating issue can you look this post for more details.
How we can resolve the datetime problem shifting the Access DB from production server to live
You can also use DateTime.ParseExact() to tell the VB code exactly what the incoming string should look like.

Categories

Resources