简体   繁体   中英

How can i convert date in specific format in javascript? Without using any library

 var options = {timeZone:'Asia/Tokyo'}; var date = new Date(1502722800000); date.toString('YYYYMMDD HH:MM'); console.log('formatted date '+date);

o/p - Mon Aug 14 2017 20:30:00 GMT+0530 (IST)

But I want o/p in this date format('YYYYMMDD HH:MM') as 20170814 17:30

toString() does not accept any arguments, and cannot be used like this. I would recommend using moment.js .

For example:

 var formatted = moment(1502722800000).format('YYYY/MM/DD h:mm'); console.log('formatted date '+formatted);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

If you wish to work with timezones, you can also add Moment Timezones .

SurisDziugas is right, with moment, you can just create and format your date like this moment(1502722800000).format('YYYYMMDD HH:MM'); I actually stopped using JS native Date object, moment offers better possibilities.

Without using any library, this can be your long solution.

 function formatDate(date) { var month = '' + (date.getMonth() + 1), day = '' + date.getDate(), year = "" + date.getFullYear(), hour = "" + date.getHours(), min = "" + date.getMinutes(); if (month.length < 2) month = '0' + month; if (day.length < 2) day = '0' + day; if (hour.length < 2) hour = '0' + hour; if (min.length < 2) min = '0' + min; return year+"/" + month +"/"+ day + " " + hour + ":" + min; } var options = { timeZone: 'Asia/Tokyo' }; var date = new Date(1502722800000); console.log(formatDate(date));

I hope this helps

The question was about a solution in JavaScript for a specific format, so without any additional libraries, a straight forward answer would be (in the style of the shim for Date.toISOString ):

function pad(number) {
    if (number < 10) {
        return '0' + number;
    }
    return number;
}

function toMyDateFormat(s) {
    return this.getUTCFullYear() +
        pad(this.getUTCMonth() + 1) +
        pad(this.getUTCDate()) +
        ' ' + pad(this.getUTCHours()) +
        ':' + pad(this.getUTCMinutes());
};

Just for curiosity, this is my shortest solution without any library:

function toMyDateFormat(d) {
    return d.toISOString().replace(/-/g,'').replace('T', ' ').substr(0,14);
}

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