1

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?

1
  • 2
    What makes this a proper format? Commented Nov 25, 2016 at 2:15

4 Answers 4

2

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('/');
}
Sign up to request clarification or add additional context in comments.

Comments

0

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");

Comments

0

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

Example

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

Hope this helps.

Comments

0
    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);

1 Comment

Please edit your answer with an explanation. Code without explanation does not make for a good answer to a question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.