1

How can I format date in AngularJS?

My date inside MySQL database is written in this format 2014-10-12 00:17:45 how can I format it in AngularJs so it will only display like this 12:17 AM - Oct. 12, 2014

I tried this solution but I got no luck https://stackoverflow.com/a/22395280/3933400 .

Also, how can I sort it from oldest to latest?

UPDATE :

The date from database was sent by PHP (JSON). Using http.get I manage to get the data. So the output is in format like this 2014-10-12 00:17:45

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

0

create a filter for EX:

app.filter('dateToISO', function() {
  return function(input) {
    input = new Date(input).toISOString();
    return input;
 };

<div>
    {{"2014-10-12 00:17:45" | dateToISO | date:'hh:mm a - MMM. dd, yyyy'}}  // filter date using
</div> 

You can sort it when you get the data from the database

Kalhan.Toress
  • 21,683
  • 8
  • 68
  • 92
0

the cross-browser solution for handling dates is like this:

First the date you receive from backend should be formatted like this: "2014-10-12T00:17:45" (Note the T), without the timezone postfix, such as (+0200). I recently did a research on this and this was the only valid format for all browsers.

Then you can create the new Date object from that date string. Then you can use Angular's date filter, or use your own if you have to. The Date object has many methods, which should easily do the job you need.

tomazahlin
  • 2,137
  • 1
  • 24
  • 29
  • should I use `timestamp` type in mysql db? –  Oct 11 '14 at 16:36
  • Datetime or timestamp, it should not be important in your case. I use JMS Serializer to serialize the data, that's why I have that "T" sign in there. – tomazahlin Oct 11 '14 at 17:38