Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

javascript - Unable to format default MySQL datetime

My dates come out of the database looking like this: 2013-11-21 17:43:20

I'm trying to user Angular's date filter to turn them into something prettier, but...

{{Objected.created | date:'shortDate'}}

or

{{Objected.created | date:'YYYY'}}

...just spits out the original datetime string: 2013-11-21 17:43:20. There are no errors. What am I doing wrong?

Update I see that MySQL's default datetime is incompatible with what Angular's data filter expects. I'm attempting to convert it on the fly like this but it's throwing errors:

<li ng-repeat="result in data">{{ new Date(result.Job.created).toISOString() | date:'shortDate'}}</li>

I suspect I can't instantiate the Date class in the way I'm trying. The error is a $parse:syntax error.

Update

Thanks to @m59's help, I got it working with a few minor adjustments...

HTML:

<html ng-app="myApp">
...
{{Object.created | dateToISO | date:'shortDate'}}

JS:

var myApp = angular.module('myApp',[]);

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

This custom filter converts the default MySQL datetime into the format that the date filter expects, so I send it throw one then another and "voila".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to convert your date string to something supported by Angular, like ISO 8601 format. You could convert it like this:

$scope.Object.created = new Date($scope.Object.created).toISOString();

Live demo here (click).

To do this on the fly, you need a custom filter. Live demo here (click).

Markup:

<div>{{Object.created | dateToISO | date:'shortDate'}}</div>

JavaScript:

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

Update:

Here's a simple way to convert your date manually (firefox):

app.filter('badDateToISO', function() {
  return function(badTime) {
    var goodTime = badTime.replace(/(.+) (.+)/, "$1T$2Z");
    return goodTime;
  };
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...