Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
840 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...