对 Javascript 中无法解析的日期进行故障排除

Troubleshooting a Date That Won't Parse in Javascript

从 C# Web 取回日期属性 API 看起来不错,但 运行 在将其插入 DevExtreme DateBox 时出现问题。它抛出了 'getFullYear is not a function' 的错误,所以我根据我在这里找到的这个函数检查了日期 -

  let r: any = http.post('/get', { Param1: 2, Param2: 1 });
  console.log(r.StartDate);  
  console.log(this.isValidDate(r.StartDate));
  r.StartDate = new Date(r.StartDate);
  r.EndDate = moment(r.EndDate);
  console.log('Start Date', this.isValidDate(r.StartDate));
  console.log('End Date', this.isValidDate(r.EndDate));

    isValidDate(d: any): void {
        if (Object.prototype.toString.call(d) === "[object Date]") {
            console.log('it is a date');
            if (isNaN(d)) { // d.getTime() or d.valueOf() will also work
                console.log('date object is not valid');
            } else {
                console.log('date object is valid');
            }
        } else {
            console.log('not a date object');
        }
    }

  StartDate: "/Date(1657512000000)/"

  not a date object
  undefined

  it is a date
  date object is not valid

  Start Date undefined
  not a date object

  End Date undefined

不确定为什么以前没有提出这个问题 API 但不想查看 DevExpress,因为我无法提供有效日期。

我提供这个答案是为了演示一种方法来解析您具有以下格式的字符串中的时间戳,由 console.log(r.StartDate); ... /Date(TS)/:[=13= 推断]

// Provided the date has the following structure in a string

var anyStartDate = "/Date(1657512000000)/";

// Prepare to parse it out by getting the positions of the parentheses

var openParens = anyStartDate.indexOf("(");
var closeParens = anyStartDate.indexOf(")");

// Parse out the timestamp

var timeStampStr = anyStartDate.substring(openParens + 1, closeParens); 

console.log( timeStampStr ); // 1657512000000

// Convert timestamp to an int. You can do this when you create the obj, but I am separating it here for explanation purposes.

var timeStampInt = parseInt( timeStampStr );

// Now create a date object

var dateObj = new Date( timeStampInt );

console.log( dateObj );

// (on the machine I'm on):
// Outputs: Mon Jul 11 2022 00:00:00 GMT-0400 (Eastern Daylight Time)
// Or outputs: 2022-07-11T04:00:00.000Z

现在我不知道您使用哪个库来处理日期,所以我只使用了本机 Date 对象。但是,您可以使用此解决方案进一步深入了解以将其应用到您的代码中。

关键是一旦时间戳被提取出来,它就可以用来创建一个 Date 对象,从而利用该 class 固有的所有方法。

就“时区”而言,要将其转换为 UTC,它已经是 UTC,但 javascript 将其格式化为您计算机的区域设置。在内部它仍然是UTC。在文档中有一种方法可以将其显示为严格的 UTC。

`