0

I have a function that I am trying to get to format the date and time or just the date at the moment.

function(){
                              var d = new Date();
                              var n = d.getTime();
                              return 'VZW Dfill - ' + n;}

What I have tried

function(){
                              var d = new Date();
                              return 'VZW Dfill - ' + d;}

This returns

VZW Dfill - Thu Jan 30 2020 103924 GMT-0500 (Eastern Standard Time)

I would like the format to be 2020JAN30

I have also tried the following but this does not work

function(){
                              var d = new Date('YYYYMDD');
                              return 'VZW Dfill - ' + d;}

The above breaks the function.

Any help is appreciated.

ellucidone
  • 21
  • 6

2 Answers2

2

This is actually surprisingly complex using pure JavaScript. Here's one (of many) solutions:

var now = new Date();
var months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
var formattedDate = now.getFullYear() + months[now.getMonth()] + now.getDate(); 
alert(formattedDate);

Using your code from above, write the following function:

function(){
                              var d = new Date();
                              var months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
                              d = d.getFullYear() + months[d.getMonth()] + d.getDate();
                              return 'VZW Dfill - ' + d;}

There is a pretty extensive thread about formatting JavaScript dates here. Most of them involve (common) third party packages.

dearsina
  • 3,332
  • 1
  • 21
  • 26
0

You can use also locale

console.log(today.toLocaleDateString("zh-TW")); // 2020/1/30
Sasho Ristovski
  • 119
  • 1
  • 6