-1

I have a month and year picker and the selection gives the value as,

const selectedValue = "10/2020"

And I need to convert the above one to 2020-10-01T06:00:00

Date in the above format can be 01 always and time can also be 06:00:00 always..

Is it possible to convert "10/2020" to 2020-10-01T06:00:00 using date format?

I have searched a lot regarding date function/methods but I couldn't find a method to achieve the above conversion. How to achieve the above type of date conversion?

James Z
  • 11,838
  • 10
  • 25
  • 41
Undefined
  • 431
  • 3
  • 14
  • 1
    Do you want to create a Date object, or just a string? – Teemu Oct 28 '20 at 11:11
  • @Teemu, I am in the need to create it as a Date object.. – Undefined Oct 28 '20 at 11:12
  • Then just use `Date` constructor: `src = selectedValue.split('/'); dte = new Date(+src[1], +src[0] - 1, 1, 6, 0, 0);`. – Teemu Oct 28 '20 at 11:14
  • [Convert the string to a date](https://stackoverflow.com/questions/5619202/converting-a-string-to-a-date-in-javascript) then [output that date as the string format you want](https://stackoverflow.com/questions/8362952/javascript-output-current-datetime-in-yyyy-mm-dd-hhmsec-format) – Liam Oct 28 '20 at 11:16
  • @Teemu, Thanks for your help.. But this gives the result as ```Thu Oct 01 2020 06:00:00 GMT+0530 (India Standard Time)``` But I am in the need of ```2020-10-01T06:00:00``` format.. – Undefined Oct 28 '20 at 11:17
  • ??? That's the date object you wanted ... If you need an ISO string, then just read the date as an ISO string. – Teemu Oct 28 '20 at 11:18
  • @Teemu, I need to send the date value back to db in the format ```2020-10-01T06:00:00``` and **not** in this ```Thu Oct 01 2020 06:00:00 GMT+0530 (India Standard Time)``` format.. – Undefined Oct 28 '20 at 11:19
  • You said you want a Date object, that is the date object. How it can be stringified in different ways you can find at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date and specifically https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString , note the UTC time in ISO string, though. – Teemu Oct 28 '20 at 11:20
  • Or if you actually don't need the Date object, make a simple template (`'YYYY-MM-01T06:00:00'`), and replace the year and the month with the values you're getting by splitting like in my second comment. – Teemu Oct 28 '20 at 13:47

1 Answers1

1

You can simply get the month and year and format it appropriately when submitting to backend as string:

const selectedValue = "10/2020";
const [month, year] = selectedValue.split('/');
const result = `${year}-${month}-01T06:00:00`;   // "2020-10-01T06:00:00"

const selectedValue = "10/2020";
const [month, year] = selectedValue.split('/');
const result = `${year}-${month}-01T06:00:00`;
console.log({ result });
Aadil Mehraj
  • 2,247
  • 4
  • 15