简体   繁体   中英

How to convert a date string in jquery to a desired format

I am getting a data string in jQuery in the following format: YYYY-MM-DD .
Now I want to show it like this: 24 Aug 2014 .
It can be done easily in php by using date function but do not know in jQuery.

$("#txt_birth_date").html(' ' + ((result.birth_date) === null) ? '' : result.birth_date));

Moment.js has great documentation.

http://momentjs.com

Date formatting or date calculation in javascript is not as straight forward as in php. I'm using the Datejs library:

I recommend you to use a library like this: https://github.com/phstc/jquery-dateFormat .

But if you want to format a string from 2014-08-24 into 24 Aug 2014 , you can wirte something like this:

function myFormatDate(d){
    var mothes   = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun','Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var d_y = d.split('-')[0];
    var d_m = d.split('-')[1];
    var d_d = d.split('-')[2];

    var mon = mothes[parseInt(d_m,10)-1];
    var dd = parseInt(d_d,10);

    if(d_y == "0000"){ // EDITED 
        return  dd + " " + mon;
    }else{
        return  dd + " " + mon + " " + d_y;
    }
}
var d = "2014-08-24";
alert(myFormatDate(d));

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM