從 C# Web API 中獲取日期屬性,這看起來不錯,但在將其插入 DevExtreme DateBox 時遇到了問題。它拋出了“getFullYear 不是一個函式”的錯誤,所以我檢查了我在這里找到的這個函式的日期 -
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。
uj5u.com熱心網友回復:
我提供這個答案是為了演示一種方法來決議您具有以下格式的字串中的時間戳,由console.log(r.StartDate);...推斷/Date(TS)/:
// 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 物件,從而利用該類固有的所有方法。
就“時區”而言,要將其轉換為 UTC,它已經是 UTC,但 javascript 會將其格式化為您計算機的區域設定。在內部它仍然是UTC。有一種方法可以在檔案中將其顯示為嚴格的 UTC。
`
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/439049.html
標籤:javascript C# 打字稿 api 网络
