我有:
export interface MyObject {
id: number;
name: string;
timestamp: number | string;
}
默认情况下,时间戳是一个数å—,但我想使用momentjs将其转æ¢ä¸ºâ€œ HH:mm:ss DD / MM / YYYYâ€æ ¼å¼çš„å—符串。
const myArray: MyObject[] = [{id: 1, name: 'foo', timestamp: 123},{id: 2, name: 'bar', timestamp: 456}];
我æ£åœ¨ä½¿ç”¨.forEach
以便将所有时间戳转æ¢ä¸ºå—符串:
myArray.forEach(el => el.timestamp = moment.unix(el.timestamp).format('HH:mm:ss DD/MM/YYYY'));
但是,我在moment.unix
呼å«ä¸æ”¶åˆ°æ¤é”™è¯¯ï¼š
 Â'string |类型的å‚æ•°æ•°å—â€ä¸èƒ½åˆ†é…给的å‚æ•°   输入“å—符串â€ã€‚ä¸èƒ½å°†â€œæ•°å—â€ç±»åž‹åˆ†é…给“å—符串â€ç±»åž‹
我在åšä»€ä¹ˆé”™ï¼Œå¦‚何解决?
ç”案 0 :(得分:1)
moment.unix
仅接å—æ•°å—作为å‚数:
https://github.com/moment/moment/blob/develop/moment.d.ts
export function unix(timestamp: number): Moment;
å› æ¤ï¼Œåœ¨å°†timestamp
ä¼ é€’ç»™moment.unix
之å‰ï¼Œè¯·ç¡®ä¿å…¶ä¸ºæ•°å—:
myArray.forEach((el) => {
const { timestamp } = el;
if (typeof timestamp === 'number') {
el.timestamp = moment.unix(timestamp).format('HH:mm:ss DD/MM/YYYY')
} else {
// will this ever happen? Do whatever you want here - ignore it, or throw
}
});
您还å¯ä»¥ä½¿ç”¨ä¸¤ç§å¯¹è±¡ç±»åž‹-一ç§ç”¨äºŽæ•°å—时间戳,一ç§ç”¨äºŽå—ç¬¦ä¸²æ ¼å¼ï¼Œå¹¶ä½¿ç”¨.map
:
export type MyObjectNumTimestamps = {
id: number;
name: string;
timestamp: number;
};
export type MyObjectStringTimestamps = {
id: number;
name: string;
timestamp: number;
};
,最åˆå°†æ•°ç»„声明为类型MyObjectNumTimestamps
,然åŽå°†å…¶è½¬æ¢ä¸ºMyObjectStringTimestamps
:
const transformedArray: MyObjectStringTimestamps[] = myArray.map(el => ({
...el,
timestamp: moment.unix(el.timestamp).format('HH:mm:ss DD/MM/YYYY')
}));