'Create UTC Timestamp in 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
Solution 1:[1]
Solution 2:[2]
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
Solution 3:[3]
function getUTCISODateString(d){
function pad(n){return n<10 ? '0'+n : n};
function threePad(n){return n<10 ? '00'+n : (n < 100 ? '0' + n : n)};
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+ '.'
+ threePad(d.getUTCSeconds()) + 'Z';
}
Not tested :
Solution 4:[4]
This library can do it for you. Not that big either http://momentjs.com
moment().toISOString()
// 2013-02-04T22:44:30.652Z
Solution 5:[5]
I would suggest extending the Date() object and building the string yourself, moment does it for you but I'm not sure it's in the exact format you need. Just wrote this up quickly, but it should be a decent starter boiler plate.
Date.prototype.toLongUTCString = function () {
var self = this;
return self.getUTCFullYear() + '-' + (self.getUTCMonth() < 10 ? '0' : '') +
(self.getUTCMonth() +1)+ '-' + (self.getUTCDate() < 10 ? '0' : '') +
self.getUTCDate() + 'T' + self.getUTCHours() + ':' + self.getUTCMinutes() +
':' + self.getUTCSeconds() + '.' + self.getUTCMilliseconds() + 'Z';
};
See more:
/edit: no one bothered to ask what browsers need to be supported (cough, IE).
Solution 6:[6]
const date = new Date()
const timestamp = date.toJSON()
const humanReadableDate = date.toLocaleString()
console.log(date) // Fri Mar 18 2022 21:22:57 GMT-0700 (Pacific Daylight Time)
console.log(timestamp) // 2022-03-19T04:22:57.983Z
console.log(humanReadableDate) // 3/18/2022, 9:22:57 PM
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Community |
| Solution 3 | |
| Solution 4 | |
| Solution 5 | konp |
| Solution 6 | jasonleonhard |
