Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
Asked Answered
M

6

80

I need to format a date as yyyy-MM-dd'T'HH:mm:ss.SSS'Z' as specified by Parse's REST API for Facebook. I was wondering what the most lightweight solution to this would be.

Mcphee answered 17/10, 2012 at 23:33 Comment(0)
Q
151

Call the toISOString() method:

var dt = new Date("30 July 2010 15:05 UTC");
document.write(dt.toISOString());

// Output:
//  2010-07-30T15:05:00.000Z
Quotation answered 17/10, 2012 at 23:40 Comment(2)
How could you go the other direction?Mellicent
@user1789573: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Quotation
U
21

toISOString() will return current UTC time only not the current local time. If you want to get the current local time in yyyy-MM-ddTHH:mm:ss.SSSZ format then you should get the current time using following two methods

Method 1:

console.log(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString());

Method 2:

console.log(new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString());
Uthrop answered 18/5, 2018 at 11:7 Comment(1)
would be better without document.write(...) around it. +1Cancel
S
7
function converToLocalTime(serverDate) {

    var dt = new Date(Date.parse(serverDate));
    var localDate = dt;
    
    var gmt = localDate;
        var min = gmt.getTime() / 1000 / 60; // convert gmt date to minutes
        var localNow = new Date().getTimezoneOffset(); // get the timezone
        // offset in minutes
        var localTime = min - localNow; // get the local time

    var dateStr = new Date(localTime * 1000 * 60);
    // dateStr = dateStr.toISOString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // this will return as just the server date format i.e., yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
    dateStr = dateStr.toString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    return dateStr;
}
Sempach answered 19/2, 2013 at 8:11 Comment(0)
K
2

Add another option, maybe not the most lightweight.

dayjs.extend(dayjs_plugin_customParseFormat)
console.log(dayjs('2018-09-06 17:00:00').format( 'YYYY-MM-DDTHH:mm:ss.000ZZ'))
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/plugin/customParseFormat.js"></script>
Kropp answered 18/12, 2020 at 5:25 Comment(0)
I
0

Node.js

const offsetInMinutes = 2 * 60 ; //Romanian
const todaysDate = new Date(new Date().getTime() + offsetInMinutes * 60000).toISOString();
Intrauterine answered 31/8, 2021 at 0:7 Comment(0)
H
-8

You can use javax.xml.bind.DatatypeConverter class

DatatypeConverter.printDateTime & DatatypeConverter.parseDateTime

Hinayana answered 9/11, 2012 at 9:5 Comment(1)
This is a Javascript question, not JavaQuitrent

© 2022 - 2024 — McMap. All rights reserved.