简体   繁体   中英

convert a datevalue returned from object to DD-MM-YYYY format

I am trying to convert the "20150812" to "12-08-2015". my returned date object shown below:

study response = [
{
    "dob": {
        "Value": [
            "20151208"
        ]
    }
} 
]

javascript function var dob = study["dob"]["Value"]; //returning 20151208 var dob = study["dob"]["Value"]; //returning 20151208

expected output //08-12-2015

tried the following: Date.parse(dob); //return NaN Date.parse(dob); //return NaN

Any help appreciated.

You can use moment js to manipulate dates. Read more: Moment.js
below code converts your string date which is in format YYYYDDMM to DD-MM-YYYY

 <script src="https://momentjs.com/downloads/moment.min.js"></script> <script> var mydate = 20151208; var str = moment(20151208,"YYYYDDMM").format('DD-MM-YYYY');//You need this line console.log(str); </script>

You can also use take substrings to get day,month and year

 var str = "20151208"; var year = str.substr(0, 4); var day = str.substr(4, 2); var month= str.substr(6,2); console.log( day+"-"+month+"-"+year);

I am trying to convert the "20150812" to "12-08-2015"

Since dob is a text string, and you want a text string result, this is probably easiest to do with text string manipulation, like this:

// var dob = study["dob"]["Value"]; //returning 20151208
var dob = "20151208";
var converted = dob.replace(/^(\d\d\d\d)(\d\d)(\d\d)$/, "$2-$3-$1");
console.log(converted);

The output will match your expected output.

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