简体   繁体   中英

Display an Exact Date in JavaScript Regardless of TimeZone

I'm writing some simple code to display birthdays of some friends. I've got the birthdays stored in a JSON file and I'm pulling them in and initializing them as Date objects like so:

birthday: new Date(p.birthday)

Then I display those dates using moment to format them, like so:

let formatted = moment(birthdayDate).format(BirthdayFormat);

This applies an automatic local time zone, probably from when I set up the initial date object, and depending on the time of day might put the date a few hours in the past, thus changing the date to the previous day since it defaults to midnight.

Basically, I just want to display that date unchanging at any time since it's just stating that person's birthday and time zones aren't relevant at all. I use it elsewhere as a Date so I don't really want to store it in the JSON as formatted, so how can I set this up such that it just acknowledges the date and doesn't adjust it for a time zone?

From your comment, the dates are in YYYY-MM-DD format. Unfortunately, ECMAScript parses such dates as UTC.

If the date has already been parsed as UTC, then you just need to display UTC values to your users. You can use momentjs's utc function (I guess this is one of its main uses):

 // Built-in parser treats YYYY-MM-DD as UTC let d = new Date('2020-12-30'); // m inherits the same time value, so is also "UTC" let m = moment(d); // Include hour H in format to show effect of utc setting later let birthdayFormat = 'dddd, D MMMM, YYYY [at] H'; // Default is local timezone, H reflects local offset // Date might be 29 or 30, depends on whether offset is - or + respectively console.log('Local: ' + m.format(birthdayFormat)); // Toggle UTC switch, all output will now be UTC, not local m.utc(); // Values are now UTC, so offset is zero and so is H // Displays Wednesday, 30 December, 2020 at 0 for all users console.log('UTC: ' + m.format(birthdayFormat));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Convert the date to the date string so that the date does not include the timezone specific value.

birthday: new Date(p.birthday).toDateString()

Then display with the momentjs

let formatted = moment(birthdayDate).format(BirthdayFormat);

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