0

hi i'm working on kind of chat project where i'm using JavaScript, by searching a long i got to know how to print today date in format of D M j G:i which prints Thu Jan 10:33, and this is in PHP, now i want same output date of D M j G:i format with JavaScript, but didn't figured it out, any helps are thank you.

unique
  • 19
  • 7
  • 1
    https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date – Berto99 Aug 05 '20 at 19:59
  • its not too simple and there is no one-liner like php, you could use a lib like moment or make something which you could prototype format method onto the date object so it works like php's, `console.log(new Date().format('ddd mmm d HH:mm'))` https://playcode.io/647163/ simplez ;p – Lawrence Cherone Aug 05 '20 at 20:07

1 Answers1

0

In JS this doesn't exist, you had to build it yourself. Get a new date an format every part out of it.
For month and day create an array with the values and get it via th index. Pay attention week begins in JS with Sunday.
For dayOfMonths, hours and minutes you had to format them because otherwise they could be only 1 digit. For this add a "0"-string before and then gets via slice the last 2-digits.

function formatDate(date) {
    const MONTH = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    const DAY = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    return DAY[date.getDay()]  + ' ' + MONTH[date.getMonth()] + ' ' + ("0" + date.getDate()).slice(-2) + ' ' + ("0" + date.getHours()).slice(-2) + ':' +  ("0" + date.getMinutes()).slice(-2);
}

let date = new Date();
console.log ( formatDate(date));
Sascha
  • 4,416
  • 3
  • 11
  • 33