0

I have this simple JavaScript function below that converts a JavaScript Date into a more readable format.

Right now you have to pass in a valid Date object but I would like to modify it so that it will accept a Date object or a string with a date value and return a formatted date regardless of which version is passed into it.

function formatDate(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return date.getMonth()+1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}

Usage:

var d = new Date(date_string);
var e = formatDate(d);

Converts this 2015-09-16 03:18:12 into 9/16/2015 3:18 pm

I want to be able to pass in a Date object...

var dateObject = new Date(date_string);
var e = formatDate(dateObject);

or a Date string...

var dateString = `2015-09-16 03:18:12`;
var e = formatDate(dateString);

2 Answers 2

2

You can check the type of variable before deciding which way to go:

function formatDate(date) {
    if(typeof(date) == "string") {
        var date_string = date;
        date = new Date(date_string);
    }
    // Then just keep going!
}
Sign up to request clarification or add additional context in comments.

Comments

1

The way to do this is to do type checking in the function via typeof.

function formatDate(date) {
  if(typeof date === "string") {
    // parse the date string into a Date object
  }
  // now date is already a Date object, or it has been parsed
  var hours = date.getHours();
  ...

Actually parsing the Date string is outside the scope of the question.

Comments

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.