本文介绍了为什么New Date()总是返回null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果日期格式为$scope.timestamp = '2016-12-16 07:02:15 am'

我想格式化为16/12/2016 07:02:15 am

我已经在下面的代码中尝试过了,并且效果很好

$scope.originalStamp = $filter('date')
                          (new Date($scope.timestamp.replace("-","/")),'dd-MM-yyyy HH:mm:ss a');

如果不使用replace().

则看到以下代码不起作用

$scope.originalStamp = $filter('date')
                              (new Date($scope.timestamp),'dd-MM-yyyy HH:mm:ss a');
解决方案

解析日期字符串,而不是 ECMA-262 中包含的ISO 8601与实施有关.您可能会得到正确的结果,错误的结果或无效的日期.因此,强烈建议不要使用 Date 构造函数或 Date.parse 来解析字符串(它们等效于解析),请始终使用库或定制函数手动解析字符串

不.约定支持多种格式(请参见 MDN日期 ),但是您不应该依赖于此,因为在某些浏览器中而不是其他浏览器中,有些解析或解析方式不同.

您可以尝试以下库之一:

  1. Moment.js :解析,格式化,算术,操作
  2. Fecha.js :仅进行解析和格式化

PS

如果您只想将'2016-12-16 07:02:15 am'格式化为'16/12/2016 07:02:15 am',则:

 // 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)) 

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');

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');
解决方案

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.

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:

  1. Moment.js: parsing, formatting, arithmetic, manipulation
  2. 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))

这篇关于为什么New Date()总是返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 22:19