0

Currently i have date in this format

cdate = 2016-06-29 23:45:42

I need to convert this date into this format

Wed 06/29/2016 11:45 PM

new Date(cdate) is giving me

Wed Jun 29 2016 23:45:42 GMT+0530 (India Standard Time)
Gergely Fehérvári
  • 7,405
  • 6
  • 43
  • 71
Matarishvan
  • 2,108
  • 3
  • 30
  • 61
  • You might consider checking [this](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) SO link. They got plenty of tips formatting dates. – Akaino Jan 02 '18 at 13:45
  • Consider simply reformatting the string, it avoids the vagaries of the built-in parser and libraries. The provided format doesn't have a timezone, so treating it as local means that it will represent a different moment in time in each host with a different offset. – RobG Jan 03 '18 at 00:14

3 Answers3

2

console.log(moment("2016-06-29 23:45:42").format("ddd MM/DD/YYYY hh:mm A"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js"></script>

You can use momentjs to format the date using format("ddd MM/DD/YYYY hh:mm A")

Durga
  • 13,489
  • 2
  • 19
  • 40
  • An answer should not involve a library that is not mentioned in the OP or tagged. If using a library, you should also provide the parse format. – RobG Jan 03 '18 at 00:13
0

More complicated, but without the 3rd party library:

let formatted = (d => {
  // Convert the date to JS string representation and split on space
  let [dow, mn, dom, year, time] = new Date(d).toString().split(/\s/);
  // Extract the month from the original string
  let [mon] = d.split('-')[0];
  // Put month, day, year in desired format
  let datestring = `${mon}/${dom}/${year}`;
  // Extract the time parts, convert to numbers
  let [hr, min, sec] = time.split(':').map(Number);
  let [hour, am] = hr > 11 ? [hr - 12, 'PM'] : [hr, 'AM'];
  return `${dow} ${datestring} ${hour}:${min} ${am}`;
})(cdate);

console.log(formatted); // Wed 2/29/2016 11:45 PM

If you need to pad month/day with zeros you can use this helper function:

let padNumber = nstring => +nstring < 10 ? `0${nstring}` : nstring;
Jared Smith
  • 14,977
  • 4
  • 36
  • 57
0

If you don't want to use any library you can use Intl. It doesn't have DOW support but you can get it pretty easily.

const date = new Date(2016, 05, 29, 11, 45);
const dow = ['Sunday','Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

console.log(`${dow[date.getDay()]} ${new Intl.DateTimeFormat('en-US', { hour: 'numeric', minute: 'numeric', month: 'numeric', year: 'numeric', day: 'numeric' }).format(date)}`);

// or with short weekday name in the host default language

console.log(`${date.toLocaleString(undefined, {weekday:'short'})} ${date.toLocaleString(undefined, {hour: '2-digit', minute: '2-digit', month: '2-digit', year: 'numeric', day: '2-digit'})}`);
RobG
  • 124,520
  • 28
  • 153
  • 188
Rodius
  • 1,959
  • 11
  • 19