super cool
super cool

Reputation: 6045

Date format convertion issue from DD-MM-YY to DD/MM/YY?

I need to display all my dates in DD/MM/YYY format .

I am doing such horrible code to achieve what i need . which is not advisable to anyone .

From my controller i get DateTime to my ViewModel(js) . so , i need to display by doing some formatting which show DateTime as Date that too in DD/MM-YY format .

Example :

From controller i get : 10-01-2014T00:00:00

In view model i need to convert like this : 10/01/2014 and display .

This is the way i am achieving and any alternative is much appreciated .

var s = data.LicenseOneTimeList[k].CompletionDate; //s = 10-01-2014T00:00:00

var len = s.length;
var d = s.substring(0, 2);
var m = s.substring(3, len - 14);
var y = s.substring(6, len - 9);    
var dateformat = new Date(y, m, d);

var month = dateformat.getMonth() > 9 ? 
dateformat.getMonth() : ("0" + (dateformat.getMonth()));
var date = dateformat.getDate() > 9 ? dateformat.getDate(): ("0" + dateformat.getDate());

var convertedDate = date + "/" + month + "/" + dateformat.getFullYear();
                                                             List.CompletionDate(convertedDate);

List.CompletionDate() will have 10-01-2014

Well i have my reasons for doing like this . Initially i tried not to split code i.e using substring but if i pass the datetime to new date( i get wrong results . I tried using date.js etc but thatwill help me while display but while posting back it will cause me serious issues .

So any possible way to shorten the above code is appreciated and any alternative is welcome .

Upvotes: 0

Views: 200

Answers (3)

Rich Pollock
Rich Pollock

Reputation: 1190

I wouldn't normally advocate this approach, but if all you need to do is display it in that format (i.e. you don't need to perform any date calculations) and you can guarantee that it's always going to come back in that exact format (dd-mm-yyyyThh:mm:ss), you could just use the following:

var convertedDate = s.substring(0, s.indexOf("T")).replace(/-/g,"/");

The Date constructor you tried is somewhat forgiving (internally it uses Date.parse()), but unfortunately your string isn't one of the recognized formats. See also RFC 2822 and the ECMAScript Date Time String format.

Upvotes: 1

Zentoaku
Zentoaku

Reputation: 767

new Date('10-01-2014').toLocaleDateString("en-US", {month: "2-digit", day:"2-digit", year: "numeric"})
"10/01/2014"

Upvotes: 0

Praveen
Praveen

Reputation: 56519

Either it is going to be date string, so there is no need to convert to Date object. So I would suggest you to simplify like

var s = data.LicenseOneTimeList[k].CompletionDate; //s = 10-01-2014T00:00:00
var dateTime_string = s.split("T");
var date_string = dateTime_string[0].replace(/-/g, "/"); // 10/01/2014

Upvotes: 1

Related Questions