kosta
kosta

Reputation: 4740

Formatting a Javascript String date to a specifc format

I have a String like 2016/1/1, which I want to change into a proper format like 2016/01/01 (yyyy/mm/dd). The output format should also be a String.

What is the correct way to do it?

Upvotes: 1

Views: 519

Answers (4)

SA Noyon Ahmed
SA Noyon Ahmed

Reputation: 123

    var now = new Date();
    var date = now.getDate();
    var month = now.getMonth() + 1;
    var monthName = ['January', 'February', 'March', 'April', 'May', 'June', 'July','August','September', 'Octobor', 'November', 'December']
    var year = now.getFullYear();
    if (date <= 9) {
        date = '0'+ date
    }
    console.log(date + '-' + monthName[month] + '-' +year);

Upvotes: 0

retype
retype

Reputation: 2385

Using Datejs, you pass a format to .toString().

Example

Date.parse('2016/1/1').toString('yyyy-MM-dd')
// "2016-01-01"

Hope this helps.

Upvotes: 0

JanR
JanR

Reputation: 6132

Handling dates in Javascript can be a pain, an alternate solution is to use momentjs

The library can be found here

You can then easily format date in various different formats using the .format() option:

var dateTime = new Date();
dateTime = moment(dateTime).format("YYYY/MM/DD");

Upvotes: 0

rfornal
rfornal

Reputation: 5122

Here's a piece of code I often use:

function yyyymmdd(dte) {
  var _date = new Date(dte);
  var mm = _date.getMonth() + 1; // getMonth() is zero-based
  var dd = _date.getDate();

  return [_date.getFullYear(),
          "/",
          (mm>9 ? '' : '0') + mm,
          "/",
          (dd>9 ? '' : '0') + dd
         ].join('');
}

var date = "1/1/2010";
yyyymmdd(dte); // returns "2010/01/01"

This is simple a format I've come up with that I like. There are probably many ways to approach this code.

This is a slightly cleaner version that was suggested to me later.

function yyyymmdd(dte) {
  var _date = new Date(dte);
  var mm = _date.getMonth() + 1; // getMonth() is zero-based
  var dd = _date.getDate();

  return [_date.getFullYear(),
          (mm>9 ? '' : '0') + mm,
          (dd>9 ? '' : '0') + dd
         ].join('/');
}

Upvotes: 2

Related Questions