简体   繁体   中英

How to convert date format in js?

I am getting the date format as

Sat Jan 28 2017 05:30:00 GMT+0530 (IST)

I want this date to be like

January 2017

Can anyone please suggest help.Thanks.

You can use the toLocaleString() on Date object

 date = new Date(); newDate = date.toLocaleString('en-US', {year: 'numeric', month: 'long'}); console.log(newDate); 

More info here: Date.prototype.toLocaleString()

TRY THIS :D

 function myFunction() { var month = new Array(); month[0] = "January"; month[1] = "February"; month[2] = "March"; month[3] = "April"; month[4] = "May"; month[5] = "June"; month[6] = "July"; month[7] = "August"; month[8] = "September"; month[9] = "October"; month[10] = "November"; month[11] = "December"; var d = new Date(); var month = month[d.getMonth()]; var year = d.getFullYear(); document.getElementById("demo").innerHTML = month+year; } 
 <button onclick="myFunction()">Try it</button> <p id="demo"></p> 

 var date = new Date('Sat Jan 28 2017 05:30:00 GMT+0530 (IST)'); var months = ["January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December" ]; console.log(months[date.getMonth()],date.getFullYear()); 

Consider using moment.js for formatting/parsing dates. This will allow you to store input/output format in config and not hardcode parser implementation. http://momentjs.com/docs/#/parsing/

var arr = ["January","February","March","April","May","June","July","August","September","October","November","December"];

var str=arr[d.getMonth()]+""+d.getFullYear();

console.log(str);

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