Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date to M j, Y? In Javascript

Tags:

javascript

Current I have this var called uniqueDate

and If I try to get the value of this variable console.log(uniqueDate);

This will give me a log in inspect element like this

["2020-05-24", "2020-05-25", "2020-05-26", "2020-05-27", "2020-05-28", "2020-05-29"]

In php there's date('M j, Y',strtotime(<data>))

that will result something like this

May 24, 2020

May 25, 2020

May 26, 2020

May 27, 2020

May 28, 2020

May 29, 2020

I want to convert the date format of var uniqueDate to M j, Y like the sample date above.

Using Jquery? or just JS

like image 540
Pablo Avatar asked Mar 09 '26 04:03

Pablo


2 Answers

You can try with this:

var date = new Date('2020-05-24');
var normalizedDate = new Date(date.getTime() - date.getTimezoneOffset() * -60000);
var formattedDate = normalizedDate.toLocaleDateString('en-US', {
    day: 'numeric',
    month: 'short',
    year: 'numeric'
});
console.log(formattedDate);

Hope it helps.

like image 151
Luis Sardon Avatar answered Mar 11 '26 18:03

Luis Sardon


var dates = ["2020-05-24", "2020-05-25", "2020-05-26", "2020-05-27", "2020-05-28", "2020-05-29"]
  var data = [];
  for (var date of dates)
  {
    date = new Date(date);
    var final = date.toDateString();
    var final = final.substring(4, 15);
    data.push(final);
  }
  console.log(data);

With this line of code 'var final = final.substring(4, 15);' The result is as following

[ 'May 24 2020',
  'May 25 2020',
  'May 26 2020',
  'May 27 2020',
  'May 28 2020',
  'May 29 2020' ]

Without this line of code 'var final = final.substring(4, 15);' it will be as following

[ 'Sun May 24 2020',
  'Mon May 25 2020',
  'Tue May 26 2020',
  'Wed May 27 2020',
  'Thu May 28 2020',
  'Fri May 29 2020' ]
like image 39
Abdul Moeez Avatar answered Mar 11 '26 18:03

Abdul Moeez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!