Reputation: 1714
I just started a new job at this software company and we realized that just a couple days ago that the dates on some of our service reports were off by a day. When I run the application on localhost all the dates are correct, so I can only speculate that the issue is coming from the server end.
We have all dates and times converted to UTC already so I don't think that this is an issue.
export const FormatDate = (stringDate) => {
if (stringDate && stringDate != "") {
var date = new Date(stringDate);
if (date.getFullYear() < 2015) { return "" }
var monthNames = ["Jan.", "Feb.", "Mar.", "Apr.", "May.", "Jun.", "Jul.", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."];
var dateToPass = monthNames[date.getMonth()] + " " + (date.getDate() ) + ", " + date.getFullYear();
if (dateToPass === "Jan. 1, 1000") {
return "";
}
return dateToPass;
}
return "";
}
This is currently how we are formatting our dates. I would assume that this wouldn't cause any issues but then again I'm slightly new to JavaScript so any suggestions would be appreciated.
Upvotes: 1
Views: 1684
Reputation: 241718
You said (in the question comments) that you are passing in strings in like this "2019-07-29T05:00:00.000Z"
. The trailing Z
indicates UTC, which is good.
You've created a Date
object by parsing this string, and then you then call the getMonth
, getDate
, and getFullYear
functions. These functions return values based on the local time zone of the computer where the code is running. Thus, you are doing a UTC to local-time conversion.
You can simply switch to the getUTCMonth
, getUTCDate
, and getUTCFullYear
functions instead. Then the results will match the value you provided in your UTC-based input string.
var dateToPass = monthNames[date.getUTCMonth()] + " " + (date.getUTCDate() ) + ", " + date.getUTCFullYear();
Upvotes: 0
Reputation: 5074
When you create a new Data
instance, you also add the current time zone according to your system.
For example, consider the following UTC time string: Mon, 29 Jul 2019 13:00:00 GMT
If you use this string to create a new Date
object and then get the local time, you may end up with a different time string
const d = new Date('Mon, 29 Jul 2019 13:00:00 GMT')
// this will return string is according to your time zone, i got 16:00:00 GMT+0300
d.toTimeString();
So you might use UTC and still get different time strings for different clients.
Upvotes: 1