Home > Net >  How to convert a string into date in typescript
How to convert a string into date in typescript

Time:08-06

i have a job for converting a string into date in TypeScript

When i tried to convert "2022-07-01" like "yyyy-MM-dd" by this code

  let temp = '2022-07-01';
  let date = new Date(temp);

It returned this value "Fri Jul 01 2022 07:00:00 GMT 0700"
But When my string is "2022-07-01 01" like "yyyy-MM-dd hh" . It turned "Invalid Value"
So my question is how can i convert ''yyyy-MM-dd hh" to Date in typeScript and can i change gmt when i convert Date? Thanks

CodePudding user response:

Easiest solution is to set a default minutes part

let temp = '2022-07-01 01';
temp  = ':00';

let date = new Date(temp);

if you need to change the timezone you must to pass all the date like this:

new Date("2015-03-25T12:00:00Z");

CodePudding user response:

According to the documentation you're giving a wrongly formatted string to the constructor. You will need to give a ISO 8601 formatted date string. A date formatted like yyyy-MM-dd hh isn't a ISO 8601 formatted date string.

Note: When parsing date strings with the Date constructor (and Date.parse, they are equivalent), always make sure that the input conforms to the ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ) — the parsing behavior with other formats is implementation-defined and may not work across all browsers. Support for RFC 2822 format strings is by convention only. A library can help if many different formats are to be accommodated.

Date-only strings (e.g. "1970-01-01") are treated as UTC, while date-time strings (e.g. "1970-01-01T12:00") are treated as local. You are therefore also advised to make sure the input format is consistent between the two types.

Working with date and time can be annoying. Fortunately there are plenty of date helper libraries you can choose from to make your life easier.

  • Related