简体   繁体   中英

Convert string to Date without considering timezone - Typescript

I'm getting a date as a string, in the following format (for example):

"11/10/2015 10:00:00"

This is UTC time.

When I create Date from this string, it consider it as local time:

let time = "11/10/2015 10:00:00";
let date = new Date(time); 
console.log(date);

it prints:

"Tue Nov 10 2015 10:00:00 GMT+0200"

(instead of considering it as UTC: "Tue Nov 10 2015 10:00:00")

I also tried moment.js for that.

is there a good way to make Date() consider the string a UTC, without adding "Z"/"UTC"/"+000" in the end of the string?

You can use the built-in Date.UTC() function to do this. Here's a little function that will take the format you gave in your original post and converts it to a UTC date string

 let time = "11/10/2015 10:00:00"; function getUTCDate(dateString) { // dateString format will be "MM/DD/YYYY HH:mm:ss" var [date, time] = dateString.split(" "); var [month, day, year] = date.split("/"); var [hours, minutes, seconds] = time.split(":"); // month is 0 indexed in Date operations, subtract 1 when converting string to Date object return new Date(Date.UTC(year, month - 1, day, hours, minutes, seconds)).toUTCString(); } console.log(getUTCDate(time)); 

Your date is parsed by the date constructor, in MM/DD/YYYY format, applying the local timezone offset (so the output represents local midnight at the start of the day in question). If your date really is MM/DD/YYYY, all you need to do is subtract the timezone offset and you'll have the UTC date...

 var myDate = new Date("11/10/2015 10:00:00"); myDate = new Date( myDate.getTime() - (myDate.getTimezoneOffset()*60*1000)); console.log(myDate.toLocaleString([],{timeZone:'UTC'})) 

Here's everything I know about managing timezone when serializing and deserializing dates. All the timezone handling is static! JS dates have no intrinsic timezone.

You can use Date.UTC for this but you will have to parse your string and put every part of it as args by yourself as it can't parse such string. Also you could use moment.js to parse it: Convert date to another timezone in JavaScript

Also, seems like new Date("11/10/2015 10:00:00 GMT") parses date as a GMT and only after that converts it to PC local time

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