0

I must to get properly date value from my long date in string.

I have this date:

Sun Aug 30 2020 00:00:00 GMT+0200 (Central European Summer Time)

how to parse this date to: 2020-08-30?

and i have another use case:

Tue Aug 25 2020 11:58:04 GMT+0200 (Central European Summer Time)

how to parse this date to: 11:58?

thanks for any help :) //////////////////////////////////////////////////////////////

XCS
  • 27,244
  • 26
  • 101
  • 151

4 Answers4

0

If you're sure that your strings are always in that format, you could just split on spaces:

date = "Sun Aug 30 2020 00:00:00 GMT+0200 (Central European Summer Time)";
[day_of_week, month, day, year, time, ...tz] = date.split(" ");
tz = tz.join(" "); // combine timezone back into one string

You could process this further, but you might want to look more into Date: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Jaden Baptista
  • 656
  • 5
  • 16
0

This would work:

const formatDate = (date) => {
  const d = new Date(date);
  let month = '' + (d.getMonth() + 1);
  let day = '' + d.getDate();
  const year = d.getFullYear();

  if (month.length < 2) {
    month = '0' + month;
  }

  if (day.length < 2) {
    day = '0' + day;
  }

  return [year, month, day].join('-');
}

// Would print 2020-08-30
console.log(formatDate('Sun Aug 30 2020 00:00:00 GMT+0200 (Central European Summer Time)'))
Kousha
  • 32,871
  • 51
  • 172
  • 296
0

You could use Date node build in lib or moment. If you’re planning to do a lot of date manipulation I would suggest use moment npm package

For getting the date version

   moment(your string).format(“YYYY-MM-DD”)

For getting the time

   moment(your string).format(“HH:mm”)
Edward Romero
  • 2,905
  • 1
  • 5
  • 17
-1
function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) 
        month = '0' + month;
    if (day.length < 2) 
        day = '0' + day;

    return [year, month, day].join('-');
}

you can use this or if you want to use 3rd party lib moment.js (https://momentjs.com/) is the best and easy to implement
rohan dani
  • 227
  • 2
  • 5
  • This is very similar to Kousha’s answer. But maybe you both copied it from the same place? – Ry- Aug 29 '20 at 20:25