2

I want to use Date Object Methods (getHoures(), getSeconds()...) on new Date("string") (string = month day, year hh:mm:ss) but my date format is like this : yyyy-mm-dd hh:mm:ss

So I need to convert "yyyy-mm-dd hh:mm:ss" to "("day, month date year hh:mm:ss")"

How can i do please ?

Thx !

Govind Singh
  • 15,282
  • 14
  • 72
  • 106
user3484934
  • 33
  • 1
  • 1
  • 4
  • is this is what you are looking for ? http://stackoverflow.com/questions/4990367/converting-a-date-string-into-utc0530-format-using-javascript – Joseph Apr 09 '14 at 10:34
  • you will get a date object if you pass the date string in "yyyy-mm-dd hh:mm:ss" format. Use the methods on that object – Quicksilver Apr 09 '14 at 10:37
  • @QuickSilver although that works on most browsers, it's not (AFAICS) one of the "officially supported" string formats. – Alnitak Apr 09 '14 at 10:38

3 Answers3

5

Try this: JSFIDDLE there are many JavaScript libraries available. format 'yyyy-mm-dd hh:mm:ss' used by MySQL server. you can covert above string into date object using following code:

var arr = " yyyy-mm-dd hh:mm:ss".split(/-|\s|:/);// split string and create array.
var date = new Date(arr[0], arr[1] -1, arr[2], arr[3], arr[4], arr[5]); // decrease month value by 1
Anoop
  • 23,044
  • 10
  • 62
  • 76
  • Sorry, couldn't get this one to work if the month comes in as 02, 03, 04 as specified by the OP. There would need to be a bit more parsing here for it to work correctly. – ariestav Jul 06 '15 at 02:33
4

Actually, you don't need to perform any such conversion.

The string you have is already in very nearly an acceptable format for new Date(string) and in fact even as is will be accepted by most (if not all) modern browsers.

To make it fully compliant with the ISO8601 variant that ES5 mandates, just replace the space between the date and time with a literal T character, and add a time-zone specifier at the end (e.g. either Z for UTC, or +01:00, for example).

See http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15 for more.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
0

Try this:

d = Date().split(" "); var date = d[2] + "-" + d[1] + "-" + d[3] + " " + d[4]

  • If you want day before this format just change the **date** variable to `var date = d[0] +","+ d[2] + "-" + d[1] + "-" + d[3] + " " + d[4]` – Modi Mohammed May 19 '17 at 14:17