Format the new date () on EEE MMM dd HH: mm: ss zzz yyyy

I have a date / time displayed using "new date ()".

Currently displayed

"Thu May 31 2012 13:04:29 GMT-0500 (CDT)". 

I need this:

  "Thu May 31 13:04:29 CDT 2012". 

How to format it?

+8
javascript date
source share
5 answers

You can use regex to extract the time zone from a standard date string.

 var d = new Date(); var customFormat = d.toString().slice(0,7) + ' ' + //Day and Month d.getDate() + ' ' + //Day number d.toTimeString().slice(0,8) + ' ' + //HH:MM:SS /\(.*\)/g.exec(d.toString())[0].slice(1,-1) //TimeZone + ' ' + d.getFullYear(); //Year 
+1
source share
 var a = new Date(); var fp = a.toDateString().substring(0, a.toDateString().length - 4); var sp = a.toLocaleTimeString(); var tp = a.toDateString().substr(a.toDateString().length - 5); $('.timer').html(fp + ' ' + sp + ' ' + tp); 
0
source share

If the string always has the format in your example:

 var s = "Thu May 31 2012 13:04:29 GMT-0500 (CDT)"; var a = s.split(/ /); s = a[0] + " " + a[1] + " " + a[2] + " " + a[4] + " " + a[6].substring(1, a[6].length - 1) + " " + a[3]; 
0
source share

The time.js library is great for formatting dates and times. http://momentjs.com/

Example: moment (). format ("MMMM Do YYYY, h: mm: ss a"); // July 14, 2015, 9:29:52 a.m.

0
source share
 // timeStamp EEE MMM d HH:mm:ss z yyyy const timeArr = new Date().toString().split('+')[0].split(' '); const timeStamp = timeArr.slice(0, 3).concat(timeArr.slice(4), timeArr[3]).join(' '); 

timeArr creates an array separated by a space. The second line reorders the order of the array to achieve this format => (EEE MMM dd HH: mm: ss zzz yyyy) using the slice and concat functions. Finally, use concatenation to convert it back to string.

0
source share

All Articles