8

This might be a simple solution but I am stuck, basically I need convert an incoming yyyy-MM-dd to MM/dd/yyyy also, if incoming date is nil, then output should also be nil.

Incoming date could be of following format

2015-01-25 or nil

Output date shoud be

01/25/2015 or nil

I was trying one from the following link Convert Date yyyy/mm/dd to MM dd yyyy but couldn't make it work.

Thanks for any help.

Forgot to mention, the incoming date which comes as nil is of the following format in an xml file

<Through_Date__c xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>

So if I get the above format the output should be just be nil

Community
  • 1
  • 1
Abhi
  • 303
  • 2
  • 5
  • 13

7 Answers7

16

The date toString function has some support for formatting. See this. And you also want to handle the undefined case which I took from here. So, for your case you can just do this:

function format(inputDate) {
    var date = new Date(inputDate);
    if (!isNaN(date.getTime())) {
        // Months use 0 index.
        return date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();
    }
}

EDIT: Addressing the comment

If the padding is important you just need to add that in:

var d = date.getDate().toString();
(d[1]?d:"0"+d[0])

I've made an update to the fiddle

Pattle
  • 5,983
  • 8
  • 33
  • 56
hassassin
  • 5,024
  • 1
  • 29
  • 38
  • return date.getMonth() + 1 should be return (date.getMonth() + 1) – user3172663 Jan 20 '17 at 05:46
  • Actually that is not needed, since it evaluates left to right it will do x.getMonth() + 1 first, then add the + '/' which will stringify. Although, I do agree that would be more readable – hassassin Jan 20 '17 at 18:44
13

Try using RegEx:

var format = function(input) {
  var pattern = /(\d{4})\-(\d{2})\-(\d{2})/;
  if (!input || !input.match(pattern)) {
    return null;
  }
  return input.replace(pattern, '$2/$3/$1');
};

console.log(format('2015-01-25'));
console.log(format('2000-12-01'));
console.log(format(''));
console.log(format(null));

Using String#split and Array#join, push & shift:

var format = function(input) {
  var array = (input || '').toString().split(/\-/g);
  array.push(array.shift());
  return array.join('/') || null;
};

console.log(format('2015-01-25'));
console.log(format('2000-12-01'));
console.log(format(''));
console.log(format(null));
  • try nicer variable names. don't use abbreviations like ptrn, just write "pattern". It's soo much easier to read! – Kinesias Jun 13 '18 at 11:42
  • in the 2nd example, line #2 can be this (without extra escape character): var array = (input || '').toString().split(/-/g); – Darren Gates May 24 '21 at 03:56
4

if you wanna go ghetto style and use easily understandable code, and you dont care about using a date object, try this!

function changeDateFormat(inputDate){  // expects Y-m-d
    var splitDate = inputDate.split('-');
    if(splitDate.count == 0){
        return null;
    }

    var year = splitDate[0];
    var month = splitDate[1];
    var day = splitDate[2]; 

    return month + '\\' + day + '\\' + year;
}

var inputDate = '2015-01-25';
var newDate = changeDateFormat(inputDate);

console.log(newDate);  // 01/25/2015
hamobi
  • 7,940
  • 4
  • 35
  • 64
3

you can deal your javascript dates in various formats.

For dd/MM/yyyy you can use

var date = new Date().toLocalDateString()

or

var date = new Date('2021-07-28').toLocalDateString()

output: '28/07/2021'

For MM/dd/yyyy

 var date = new Date().toLocaleDateString("en-US", { year: "numeric", month: "2-digit", day: "2-digit" })

or

 var date = new Date('2021-07-28').toLocaleDateString("en-US", { year: "numeric", month: "2-digit", day: "2-digit" })

output: '07/28/2021'

Alternatively you can handle custom date formats using following date functions

let date = new Date()
let dateString = [
            date.getMonth() + 1,
            date.getDate(),
            date.getFullYear(),
        ].join('/')
    }

output: 07/28/2021

sarath chandra
  • 181
  • 1
  • 4
1

If your date has not yet been parsed from a string, you can simply rearrange its components:

var s = '2015-01-25';
if (s) { 
    s = s.replace(/(\d{4})-(\d{1,2})-(\d{1,2})/, function(match,y,m,d) { 
        return m + '/' + d + '/' + y;  
    });
}
Ben Grimm
  • 4,316
  • 2
  • 15
  • 24
0

Thanks guys, I was able to do grab some ideas from all your posts and came up with this code which seems to working fine in my case

if((typeof inStr == 'undefined') || (inStr == null) || 
(inStr.length <= 0)) {
return '';
}
var year = inStr.substring(0, 4);
var month = inStr.substring(5, 7);
var day = inStr.substring(8, 10);
return month + '/' + day + '/' + year;
Abhi
  • 303
  • 2
  • 5
  • 13
0

You can also try the method below using vanilla JS. I have converted the date to a string & parsed it to get the format you're looking for:

function tranformDate(strDate) {
    let result = '';

    if (date) {
      let parts = date.split('-');
      result = `${parts[1]}/${parts[2]}/${parts[0]}`;
    }
    return result;
}

let date = new Date().toISOString().split('T')[0];
console.log('raw date: ' + date);
console.log('formatted date: ' + tranformDate(date));
Hamzeen Hameem
  • 2,360
  • 1
  • 27
  • 28