Jhon
Jhon

Reputation: 111

how to change the date format using jquery

I have a input date field whose value is in this "2014-06-07 07:14"(year-month-date hour:minute) format how can i change it to 06/07/2014 07/14( mm/dd/yy) format using jquery.

Upvotes: 2

Views: 1099

Answers (2)

hlscalon
hlscalon

Reputation: 7552

Why using jQuery to do this ?

Use plain js:

var date = new Date('2014-06-07 07:14');
alert((date.getMonth() + 1) + '/' + date.getDate() + '/' +  date.getFullYear() + ' ' +          date.getHours() + '/' + date.getMinutes());

http://jsfiddle.net/F4nq8/

It seems that IE and Safari have some bug with YYYYMMDD dates so a workaround could be something like:

var s = "2014-06-07 07:14";
var t = s.split(" ");
var d = t[0].split("-");
var x = d[1] + "/" + d[2] + "/" + d[0] + " " + t[1];
var date = new Date(x);
alert((date.getMonth() + 1) + '/' + date.getDate() + '/' +      date.getFullYear() + ' ' + date.getHours() + '/' + date.getMinutes());

http://jsfiddle.net/F4nq8/4/

Some reference about this behaviour: http://biostall.com/javascript-new-date-returning-nan-in-ie-or-invalid-date-in-safari

Upvotes: 2

Augustus Francis
Augustus Francis

Reputation: 2670

DateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("dd/MM/yyyt hh/mm");
Date date = originalFormat.parse("2014-06-07 07:14");
String formattedDate = targetFormat.format(date);  // 06/07/2014 07/14

Docs of SimpleDateFormat#format

PS: A JavaScript implementation of the format() method of Java's SimpleDateFormat: is available here

Upvotes: 2

Related Questions