Home > Software engineering >  Javascript, trying to get date part time only
Javascript, trying to get date part time only

Time:03-27

I have a date field coming from SQL as follows:

2022-06-30T00:00:00.000Z

Im trying to get the first 10 characters (date in format yyyy-mm-dd) from it, but I can't get it to work.

First, I tried a "left" function

textPaidThru= pt.slice(0,10)

And I got

Wed Jun 29

Then I tried moment

let textPaidThru = moment(paidThru).format('YYYY-MM-DD');

But Im getting this:

2022-06-29

No matter which method I try to use, I always get the provided date minus one day.

I encounter working with dates very hard in JS. Is there a way to get the date part only as provided by SQL? This is the value Im expecting:

2022-06-30

Thanks.

CodePudding user response:

TL;DR; Timezones

Actual Answer

You could just use some vanilla javascript and parse it like this:

Note month is zero index in Date, so you will need to add 1 to each:

const dateToParse = "2022-06-30T00:00:00.000Z"
let parsedDate =  new Date(dateToParse)
const formattedDate = `${parsedDate.getFullYear()}-${parsedDate.getMonth() 1}-${parsedDate.getDate()}`
console.log(formattedDate)

The reason you are getting 6-29 is most likely due to you not living in UTC 0. I get 6-29 as well, but that is because I live in UTC-7.

If you look in the code below I change the time to be UTC-7 (which should work for your timezone as well if what your profile says is correct UTC-3) and the console log for me displays 6-30 now.

const dateToParse = "2022-06-30T07:00:00.000Z"
let parsedDate =  new Date(dateToParse)
const formattedDate = `${parsedDate.getFullYear()}-${parsedDate.getMonth() 1}-${parsedDate.getDate()}`
console.log(formattedDate)

CodePudding user response:

If you know you'll always get the same format (well, you probably will), you can just use split, something like.

let dateTime = '2022-03-25T02:03:04.000Z';
let onlyDate = date.split('T')[0];

This will split the string at T and you basically only want the first part (array index 0) and that's it.

  • Related