10
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" ?

Ridwanul Hafiz
  • 181
  • 1
  • 1
  • 11
  • 1
    A question arises, why would `10:54:11` be `at 10:51` ? – adeneo Jul 12 '14 at 11:10
  • 1
    Why "in jQuery"? This has nothing to do with jQuery. – RobG Jul 12 '14 at 13:11
  • 1
    @RidwanulHafiz Check the updated answer (2nd solution). Here is the [jsBin](http://jsbin.com/zilejoyo/1/edit?js,console) In the meantime I'll review the whole answer and let you know if I find something better :) – hex494D49 Jul 12 '14 at 14:22

5 Answers5

14
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]
hex494D49
  • 9,109
  • 3
  • 38
  • 47
  • But when var d = "2014-07-12 11:28:13"; it doesn't work. I have to change "2014-07-12 11:45:31" to "12 Jul, 2014 at 11:45 am" – Ridwanul Hafiz Jul 12 '14 at 11:46
  • I see, I'll update the function :) I thought you will use for current date – hex494D49 Jul 12 '14 at 11:49
  • @RidwanulHafiz Check the 2nd solution – hex494D49 Jul 12 '14 at 11:58
  • It returns "NaN undefined, NaN invalid date" – Ridwanul Hafiz Jul 12 '14 at 12:08
  • @RidwanulHafiz Have you checked the jsBin (the link provided)? – hex494D49 Jul 12 '14 at 12:13
  • It's working in google chrome well , but in firefox it shows "NaN undefined, NaN invalid date" I don't know why .... :( – Ridwanul Hafiz Jul 12 '14 at 12:17
  • 1
    @RidwanulHafiz Done :) Check [jsBin](http://jsbin.com/cigiwemu/4/edit?js,console) I'll explain the reason in a minute – hex494D49 Jul 12 '14 at 12:27
  • @RidwanulHafiz Thank you! :) Check the extra note I just added to the answer; I din't know that some formats aren't supported in all browsers. – hex494D49 Jul 12 '14 at 12:35
  • Now It's working like "2014-07-12 11:45:31" to "12 Jul, 2014 at 11:45:31 am" Is it possible to make it like "2014-07-12 11:45:31" to "12 Jul, 2014 at 11:45 am" – Ridwanul Hafiz Jul 12 '14 at 12:46
  • @RidwanulHafiz I see, you won't seconds in. I'll do it in a couple of minutes and drop you a note. – hex494D49 Jul 12 '14 at 12:52
  • This answer is dependent on *Date.parse* and a non–standard date string format and therefore should not be recommended. – RobG Jul 12 '14 at 12:54
  • The use of *toString* in `d.getDay().toString()` is completely unnecessary since `+` will convert it to a string, and in `d.toLocaleTimeString().toString()` is redundant, as is *Date.parse* in `new Date(Date.parse(...))`, and *d.toLocaleTimeString()* does not return *am* or *pm* in all browsers, it's implementation dependant and may return different results in different browsers. – RobG Jul 12 '14 at 13:05
  • @RobG You're right about the `toString()` - it just left while I was coding/editing - but I know that :) – hex494D49 Jul 12 '14 at 13:11
2

I've made a custom date string format function, you can use that.

var  getDateString = function(date, format) {
        var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        getPaddedComp = function(comp) {
            return ((parseInt(comp) < 10) ? ('0' + comp) : comp)
        },
        formattedDate = format,
        o = {
            "y+": date.getFullYear(), // year
            "M+": months[date.getMonth()], //month
            "d+": getPaddedComp(date.getDate()), //day
            "h+": getPaddedComp((date.getHours() > 12) ? date.getHours() % 12 : date.getHours()), //hour
             "H+": getPaddedComp(date.getHours()), //hour
            "m+": getPaddedComp(date.getMinutes()), //minute
            "s+": getPaddedComp(date.getSeconds()), //second
            "S+": getPaddedComp(date.getMilliseconds()), //millisecond,
            "b+": (date.getHours() >= 12) ? 'PM' : 'AM'
        };

        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                formattedDate = formattedDate.replace(RegExp.$1, o[k]);
            }
        }
        return formattedDate;
    };

And now suppose you've :-

    var date = "2014-07-12 10:54:11",
    objDate = Date.parse(date.replace(/-/g, "/"));;

So to format this date you write:-

var formattedDate = getDateString(new Date(objDate ), "d M, y at h:m b")
Indranil Mondal
  • 2,799
  • 3
  • 25
  • 40
0

You can try this:

http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3

or this plugin

https://github.com/phstc/jquery-dateFormat

or

refer this SO answer: jQuery date formatting

Community
  • 1
  • 1
K K
  • 17,794
  • 4
  • 30
  • 39
0

Is there any function like

No. You have to format it yourself. You have two options: parse the string to create a Date object and generate a formatted string from that, or just use the parts of the string and reformat it. In both cases, it is assumed that you want to treat it as a local date.

Do not be tempted to do:

var d = new Date('2014-07-12 10:54:11')

as some browsers will treat it as UTC, some as local and others won't parse it at all. The following will convert the string to the requested format without creating a Date object:

function formatDate(s){
  var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  var b = s.split(/\D+/);
  return b[2] + ' ' + months[+b[1]] + ', ' + b[0] + ' at ' + (b[3]%12 || 12) +
         ':' + b[4] + ' ' + (b[3] < 12? 'am':'pm');
}

However, if you need to create a Date object for some other reason, the following may help:

function formatDate(s){
  function z(n){return (n<10?'0':'')+n}
  var months = ['Jan','Feb','Mar','Apr','May','Jun',
                'Jul','Aug','Sep','Oct','Nov','Dec'];
  var b = s.split(/\D+/);
  var d = new Date(b[0],--b[1],b[2],b[3],b[5],b[5]);
  return d.getDate() + ' ' + months[d.getMonth()] + ', ' + d.getFullYear() +
         ' at ' + z(d.getHours()%12 || 12) + ':' + z(d.getMinutes()) +
         ' ' + (d.getHours() < 12? 'am':'pm');
}
RobG
  • 142,382
  • 31
  • 172
  • 209
0
function convertMysqldate(dateStr) {    // Assuming input:2014-01-30 16:21:09
            var t = dateStr.split(/[- :]/);
            var monthNames = ["January", "February", "March", "April", "May", "June",
                "July", "August", "September", "October", "November", "December"];
            var year = t[0];
            var month = monthNames[parseInt(t[1])];
            var day = t[2];
            var hourTmp = t[3];
            var minute = t[4];
            var seconds = t[5];
            if (parseInt(hourTmp) > 12) {
                var hour = parseInt(parseInt(hourTmp) – 12) + ‘:’ + minute + ‘:’ + seconds + ‘ PM’;
            } else if (parseInt(hourTmp) === 12) {
                hour = parseInt(hourTmp) + ‘:’ + minute + ‘:’ + seconds + ‘ PM’;
            } else {
                hour = parseInt(hourTmp) + ‘:’ + minute + ‘:’ + seconds + ‘ AM’;
            }
            return (hour + ‘<br>’ + day + ‘ ‘ + month + ‘ ‘ + year);
        }

Copied from here

MySql Date formatting

Confused
  • 1,602
  • 15
  • 25