From the server I get a datetime variable in this format: 6/29/2011 4:52:48 PM
and it is in UTC time. I want to convert it to the current user’s browser time us
This is an universal solution:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
Usage:
var date = convertUTCDateToLocalDate(new Date(date_string_you_received));
Display the date based on the client local setting:
date.toLocaleString();
To me the simplest seemed using
datetime.setUTCHours(datetime.getHours());
datetime.setUTCMinutes(datetime.getMinutes());
(i thought the first line could be enough but there are timezones which are off in fractions of hours)
I believe this is the best solution:
let date = new Date(objDate);
date.setMinutes(date.getTimezoneOffset());
This will update your date by the offset appropriately since it is presented in minutes.
For the TypeScript users, here is a helper function:
// Typescript Type: Date Options
interface DateOptions {
day: 'numeric' | 'short' | 'long',
month: 'numeric',
year: 'numeric',
timeZone: 'UTC',
};
// Helper Function: Convert UTC Date To Local Date
export const convertUTCDateToLocalDate = (date: Date) => {
// Date Options
const dateOptions: DateOptions = {
day: 'numeric',
month: 'numeric',
year: 'numeric',
timeZone: 'UTC',
};
// Formatted Date (4/20/2020)
const formattedDate = new Date(date.getTime() - date.getTimezoneOffset() * 60 * 1000).toLocaleString('en-US', dateOptions);
return formattedDate;
};
This works for me:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime() - date.getTimezoneOffset()*60*1000);
return newDate;
}
You can use momentjs ,moment(date).format()
will always give result in local date.
Bonus , you can format in any way you want. For eg.
moment().format('MMMM Do YYYY, h:mm:ss a'); // September 14th 2018, 12:51:03 pm
moment().format('ffffdd'); // Friday
moment().format("MMM Do YY");
For more details you can refer Moment js website