Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
974 views
in Technique[技术] by (71.8m points)

format date to MMMYYYY JavaScript

I would like to format a date to be in the date format of MMMYYYY. For example, if "Tue Jan 26 2021 12:45:59 GMT+0300" is being returned from new Date(), then I would like it to be displayed as "Jan2021". How can I do that using JS? Thanks.

question from:https://stackoverflow.com/questions/65899053/format-date-to-mmmyyyy-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the built-in date functions of Javascript and get the desired output. Like below code snippet:

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ];

let date = new Date();
// For Jan month, getMonth will return 0. 
const currentMonth = date.getMonth();
const dateStr = months[currentMonth] + date.getFullYear();
console.log(dateStr);

JS Fiddle: https://jsfiddle.net/sagarag05/1bsj39ah/7/

Kindly note, the month names are in English. So they are not localised in case if you have those constraints, that is not considered here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...