-2

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

Phạm Cường
  • 59
  • 3
  • 11

2 Answers2

2

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");

btafarelo
  • 601
  • 3
  • 12
  • Thanks guy it's working well. So can i change the GMT when coverting like this? – Phạm Cường Aug 05 '22 at 12:07
  • yes, this thread has many sample that will be helpful to you. https://stackoverflow.com/questions/15141762/how-to-initialize-a-javascript-date-to-a-particular-time-zone – btafarelo Aug 05 '22 at 12:20
1

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.

Thijs
  • 3,015
  • 4
  • 29
  • 54