Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format date time in jQuery

var date = "2014-07-12 10:54:11";

How can I show this in format 12 Jul, 2014 at 10:51 am ? Is there any function like

var newDate = formatNewDate(date);

From which I can able to get the date time as "12 Jul, 2014 at 10:51 am" ?

like image 352
Ridwanul Hafiz Avatar asked Mar 28 '26 17:03

Ridwanul Hafiz


1 Answers

var d = new Date();
var month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

var date = d.getDate() + " " + month[d.getMonth()] + ", " + d.getFullYear();
var time = d.toLocaleTimeString().toLowerCase();

console.log(date + " at " + time);
// 6 Jul, 2014 at 1:35:35 pm

Or you can have a function

var my_date_format = function(d){
    var month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var date = d.getDate() + " " + month[d.getMonth()] + ", " +  d.getFullYear();
    var time = d.toLocaleTimeString().toLowerCase();
    return (date + " at " + time); 
}(new Date());

Usage:

console.log(my_date_format);

2nd solution

var my_date_format = function(input){
    var d = new Date(Date.parse(input.replace(/-/g, "/")));
    var month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var date = d.getDate() + " " + month[d.getMonth()] + ", " + d.getFullYear();
    var time = d.toLocaleTimeString().toLowerCase().replace(/([\d]+:[\d]+):[\d]+(\s\w+)/g, "$1$2");
    return (date + " " + time);  
};

console.log(my_date_format("2014-07-12 11:28:13"));
// output 6 Jul, 2014 11:28 am

Check the jsBin

Extra note: Some of date formats aren't supported in all browsers!

// "2014/07/12"      -> yyyy/mm/dd [IE, FF, Chrome]
// "07-12-2014"      -> mm-dd-yyyy [IE, Chrome]
// "July 12, 2014";  -> mmmm dd, yyyy [IE, FF]
// "Jul 12, 2014";   -> mmm dd, yyyy [IE, FF]
like image 121
hex494D49 Avatar answered Mar 30 '26 08:03

hex494D49



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!