简体   繁体   中英

how to convert a date time string unto a specified date time format

Anyone knows how to convert this

Wed Dec 02 2015 00:00:00 GMT+0800 (China Standard Time)

to

2015-12-02 00:00:00

any ideas, help, clues, suggestions, recommendations will be greatly appreciated.

Try this:

var temp = new Date("Wed Dec 02 2015 00:00:00 GMT+0800 (China Standard Time)");
console.log(temp.getFullYear() + "-"  +(temp.getMonth() + 1) + "-" + temp.getDate());
console.log(temp.getHours() + ":" + temp.getMinutes() + ":" + temp.getSeconds());
var d = Date.parse("Wed Dec 02 2015 00:00:00 GMT+0800");
d = new Date(d).toLocaleString();

use this then:

var d = Date.parse("Wed Dec 02 2015 00:00:00 GMT+0800");
d = new Date(d).toLocaleString();
d.replace(/\d+\/\d+\/\d{4},/, function (x){
   x = x.replace(/,/, "");
   x = x.split("/");
   return x[2] + "-" + x[1] + "-" + x[0]; 
});

Sorry, had to run downstairs. Forget the regex, just slice it up and use it together like this. ( http://jsfiddle.net/u2xn2Lv5/1/ )

JS:

var origTime = "Wed Dec 02 2015 00:00:00 GMT+0800 (China Standard Time)";
//or function you call to derive this data stringified

var dayVal = origTime.slice(8,10);
var yearVal = origTime.slice(11,15);
var monthVal = origTime.slice(4,7);
var timeVal = origTime.slice(16,23);
var newDate = ""; // Hasn't been set yet
//alert(monthVal);
switch(monthVal) {
    case "Dec":
        newDate = "12";
        break;
    case "Jan":
        newDate = "1";
        break;
    case "Jun":
        newDate = "6";
        break;
    default:
        "unknown month!"
};

var newTime =  newDate + "-" + dayVal + "-" + yearVal + "-" + timeVal;
document.getElementById("spanthing").innerHTML = newTime;

HTML:

<div id="spanthing"></div>

To be rearranged as needed! Cheers!

Just go with moment.js .

var time = 'Wed Dec 02 2015 00:00:00 GMT+0800 (China Standard Time)';
var format = moment(time).format('YYYY-MM-DD HH:mm:ss');

Here is jsfiddle .

你可以试试这个

moment(yourDate).format("YYYY-MM-DD HH:mm:ss");

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