2

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.

7
  • 3
    Take a look at moment.js Commented Jun 6, 2014 at 14:20
  • why would someone downvote this? Completely valid question Commented Jun 6, 2014 at 14:21
  • is the first date a string? and the second a date object? Commented Jun 6, 2014 at 14:21
  • look at this library github.com/minagabriel/dtmFRM this library do the exact same thing as C# .tostring() date time format Commented Jun 6, 2014 at 14:21
  • Yes please let me know you it is down voted. is it only because i am new to jquery? Commented Jun 6, 2014 at 14:22

2 Answers 2

2
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

Sign up to request clarification or add additional context in comments.

Comments

2

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

4 Comments

@user3341149 have you checked the jsfiddle link in the description ?
Even if var date = new Date('2014-06-07 07:14'); console.log(date); saying invalid date.
What browser,version are you using ?
Still not working on firefox. please check the below answer its working fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.