JavaScript Date Format

tmajor99 used Ask the Experts™
Need help with a simple JavaScript that will reformat a date string.  I currently have the variable containing a date string in CCYY-MM-DD format.  I need to change this format to mm/dd/ccyy.

var revision = node.getRevision();              
var MyDate = node.getValue("UPDT_DATE").GetSimpleValue(ScriptHelper.getISODate(revision.getCreated()));

//MyDate is formatted as  CCYY-MM-DD.  I need to change to MM/DD/CCYY.
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Below I have replicated the extraction of the value of UPDT_DATE by setting the value of MyDate directly (as 27 August 2015) within [CCYY-MM-DD] format.

I have then transposed the digits & output the MyDate variable within the required format [MM/DD/CCYY]:

//var revision = node.getRevision();
//var MyDate = node.getValue("UPDT_DATE").GetSimpleValue(ScriptHelper.getISODate(revision.getCreated()));

  var MyDate = new Date('2015-08-27');

  var MyDate = ((MyDate.getMonth()<9)?'0':'') + (MyDate.getMonth() + 1) + '/' + ((MyDate.getDate()<10)?'0':'') + MyDate.getDate() + '/' + MyDate.getFullYear();


Open in new window

Most Valuable Expert 2017
Distinguished Expert 2018
You can subclass the Date object to add your own format method and then use string concatenation and split to 0 pad the date
Date.prototype.myFormat = function() {
  var dateString =  
    ("0" + (this.getMonth()+1)).slice(-2) +"-"+ // 0 pad month
    ("0" + this.getDate()).slice(-2) + " " +    // 0 pad day

  return dateString;
var d = new Date();
alert (d.myFormat());

Open in new window

IT Professional
Top Expert 2015
I think default format of date object in Javascript is "mm/dd/yyyy" format!

You do not need to do anything extra, just give date string into Date object and use it's inbuilt functions like below:
var dt = new Date('2015-08-31');
//complete date alongwith time
document.write('date is:'+dt);
//Result=> date is:Mon Aug 31 2015 05:30:00 GMT+0530 (India Standard Time)

//Date with localDateString (Local can be use to set the format of date like
// for "en-US" => 'mm/dd/yyyy' and "en-GB" => 'dd/mm/yyyy'
document.write('<br/>date is:'+dt.toLocaleDateString('en-US'));
//Result=> date is:8/31/2015

//Complete date with time  in local format
document.write('<br/>date is:'+dt.toLocaleString('en-US'));
//Result=> date is:8/31/2015, 5:30:00 AM

Click below link to check with Javascript documentation

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial