I have been struggling to change the date format to US locale time. I tried so many methods but if fails at some or other scenario. The issue is I cannot say which Locale the client will be using. If anybody can help me it will be great.
I have tried the $A.localizationService.formatDate(sDate, "yyyy-MM-dd")
but when the date comes like this '31.3.2018' it throws error.
Even tried this as well new Date(sDate)
. it throws Invalid Date Error for date '31.3.2018' but it works if the date is less or equals to 12 suppose '10.2.2018' or '2.10.2018'.
So I tried to write a method which converts the date to "yyyy-MM-dd" format. So far what I have tried.
formatDate : function(date) {
if(typeof(date) != 'string') {
return $A.localizationService.formatDate(date, "yyyy-MM-dd");
}
if(date != null && date.search("-") > -1){
return date;
}
var regex = /[^a-zA-Z0-9]/g;
var specialcharacter = '-';
date = date.replace(regex, specialcharacter);
var dateparts = date.split(specialcharacter);
if(dateparts == null || dateparts.length <= 1) {
return $A.localizationService.formatDate(new Date(), "yyyy-MM-dd");
}
if(dateparts[0].length == 4){
date = new Date(parseInt(dateparts[0]), parseInt(dateparts[1] - 1), parseInt(dateparts[2]));
}
else{
date = new Date(parseInt(dateparts[2]), parseInt(dateparts[1] - 1), parseInt(dateparts[0]));
}
return $A.localizationService.formatDate(date, "yyyy-MM-dd");
}
anywhere in my controller.js I have passing date to the above function which converts the date to "yyyy-MM-dd" format. I tried with Finnish locale in Dev org it is working as expected but when we installed this on sandbox it was giving us the error.
Let me know if something else is required from my side.