Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create UTC Timestamp in Javascript

Tags:

javascript

I am trying to send UTC time-stamp to rest service from my javascript client. i was not able to create time-stamp like "2013-08-30T19:52:28.226Z" using javascript.

var rawDate = date.getUTCDate().toString();

i see this example but not helpful for me. utc-time-stame-javascript

like image 930
Shashank Shukla Avatar asked Aug 31 '13 08:08

Shashank Shukla


2 Answers

You can use date.toJSON().

new Date().toJSON()
"2013-08-31T09:05:07.740Z"

See MDN or MSDN

like image 125
Benoit Blanchon Avatar answered Nov 15 '22 16:11

Benoit Blanchon


1) Get the date.

var now = new Date();

2) Convert to UTC format like below, for reference.

var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), 
                  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());

3) Using toJSON, get the format.

now_utc.toJSON()

Finally,

var now = new Date();
var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
alert(now_utc.toJSON());

Check this JSFiddle

like image 41
Praveen Avatar answered Nov 15 '22 17:11

Praveen