-1

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

2
  • You can try googling for solutions and trying them out. Commented Aug 5, 2022 at 11:49
  • Hey, you can check this link. You should handle each datetimeformat one by one. stackoverflow.com/a/43202323/8763644 Commented Aug 5, 2022 at 11:50

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks guy it's working well. So can i change the GMT when coverting like this?
yes, this thread has many sample that will be helpful to you. stackoverflow.com/questions/15141762/…
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.

1 Comment

Thanks for your infomation. It's help me a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.