0

I am trying to format a mysql datetime object in Javascript, but I only get NaN results.

The value from the database is for example this datetime object:

2015-08-27 21:36:03

In my JS I try to convert this object as follows:

var formattedDate = new Date(datetimeObj);

function formatDate(date) {
                var hours = date.getHours();
                var minutes = date.getMinutes();
                hours = hours % 12;
                hours = hours ? hours : 12; // the hour '0' should be '12'
                minutes = minutes < 10 ? '0'+minutes : minutes;
                var strTime = hours + ':' + minutes;
                return date.getMonth()+1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}

How come that I when printing the variable, I get NaN/NaN/NaN 12:NaN?

Max
  • 832
  • 1
  • 14
  • 33
  • Are you really passing a valid *string* to the Date constructor ? – Denys Séguret May 21 '15 at 10:05
  • use http://momentjs.com it will let you convert to whatever you want :) – blairmeister May 21 '15 at 10:09
  • The object I am passing (= datetimeObj) contains the following according to FF web console: `Object { date: "2015-05-19 08:54:36.000000", timezone_type: 3, timezone: "Europe/Berlin" }` – Max May 21 '15 at 10:09

3 Answers3

1

Some browsers will not parse the string "2015-08-27 21:36:03" as a valid date. For best results, use a standard ISO date string, as in

2015-08-27T21:36:03Z 
0

Try this:

<script>
  var formattedDate = new Date("2015-08-27 21:36:03");
  console.log(formatDate(formattedDate));
  function formatDate(date)
  {
    var hours = date.getHours();
    var minutes = date.getMinutes();
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0' + minutes : minutes;
    var strTime = hours + ':' + minutes;
    return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
  }
</script>

Its the same code, just passed the input in your function..

Rayon
  • 36,219
  • 4
  • 49
  • 76
0

Here you can find answer on your quetions, it something like this with RegEx

var dateString = "2010-08-09 01:02:03";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString); 
var dateObject = new Date(
    (+dateArray[1]),
    (+dateArray[2])-1, // Careful, month starts at 0!
    (+dateArray[3]),
    (+dateArray[4]),
    (+dateArray[5]),
    (+dateArray[6])
);
Community
  • 1
  • 1
The Reason
  • 7,705
  • 4
  • 24
  • 42