问题
If a date format is $scope.timestamp = '2016-12-16 07:02:15 am'
I want to format to 16/12/2016 07:02:15 am
I have tried this below code and it's working good
$scope.originalStamp = $filter('date')
(new Date($scope.timestamp.replace("-","/")),'dd-MM-yyyy HH:mm:ss a');
But my question is why
new Date($scope.timestamp)is always returnnullif am not use replace the char from (-) to (/)?
see the below code is not working if am without using replace().
$scope.originalStamp = $filter('date')
(new Date($scope.timestamp),'dd-MM-yyyy HH:mm:ss a');
Why the
new Date()does not accept if the date format having (-)? Is new Date() conversion is depend by my system date format?
回答1:
Why the new Date() does not accept if the date format having (-)?
Parsing of date strings other than the limited subset of ISO 8601 included in ECMA-262 is implementation dependent. You may get the correct result, an incorrect result or an invalid date. Therefore it is strongly recommended not to use the Date constructor or Date.parse to parse strings (they are equivalent for parsing), always manually parse strings with a library or bespoke function.
Is new Date() conversion is depend by my system date format?
No. There are a number of formats that are supported by convention (see MDN Date), however you should not rely on that as some are parsed, or parsed differently, in some browsers but not others.
You might try one of these libraries:
- Moment.js: parsing, formatting, arithmetic, manipulation
- Fecha.js: just parsing and formatting
PS
If you just want to reformat '2016-12-16 07:02:15 am' as '16/12/2016 07:02:15 am', then:
// Reformat a date like '2016-12-16 07:02:15 am' as
// '16/12/2016 07:02:15 am'
function reformatDate(s) {
var b = s.split(/[ -]/);
return [b[2],b[1],b[0]].join('/') + ' ' + b[3] + ' ' + b[4];
}
var s = '2016-12-16 07:02:15 am';
console.log(s + ' => ' + reformatDate(s))
来源:https://stackoverflow.com/questions/41583164/why-new-date-is-always-return-null