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)
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)
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")
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;
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'})}`);