简体   繁体   中英

Javascript date formatting to local timezone with specific format

I have a date string which is in UTC timezone like this 2015-05-26T14:02:46.000Z

I will convert this to a date object using

var lastModified = "2015-05-26T14:02:46.000Z;
var date = new Date(lastModified);

But when I print this, it prints the date like this Tue May 26 2015 19:32:46 GMT+0530 (India Standard Time)

I want to print the date like this 2015-05-26 7:32:46 PM IST or 2015-05-26 7:32:46 PM GMT+0530

Is there any way to do this?

As hindmost says, it's pretty simple in pure JS. But if you'll be doing this a lot, you may want to look into the powerful MomentJS library.

Using Moment, your code would just be:

moment(date).format('YYYY-MM-DD HH:mm:ss A [GMT]Z')

Date has a number of getter method to get the components of a date. For example date.getHours() will return a number from 0 to 23 for the hour of the day. With each of these pieces you can write the logic to display the date in the format you choose. See the methods Date has here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

If you're looking for a library, MomentJS is the best library I've used for time and dates. It might be too heavy for your needs though. Consider use cases carefully before adding another somewhat large dependency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM