我一直在研究日期中是否有单独的字符串作为
date = 18-9-2018
时间为
time= 01:50 PM
,如果我想创建上述两个变量的时间戳,我如何 应该有那个?
当前的问题是我正在从API端点接收这些变量,并且我需要具有确切的时间戳,以便可以将其用作本地提醒通知确切的日期和时间!
这是我到目前为止尝试过的
createTheLocalAlert(appointments) {
// Schedule delayed notification
appointments.description.forEach(appointment => {
let notificationText =
`you have meeting with ${appointment.name} today at ${appointment.meeting_start}`;
let theDate = appointment.appointment_date.split("-");
let newDate = theDate[1] + "/" + theDate[0] + "/" + theDate[2];
let DateWithTime = newDate + appointment.meeting_start;
// alert(new Date(newDate).getTime()); //will alert 1330210800000
// console.warn("theTime_is===>" + new Date(DateWithTime));
this.localNotifications.schedule({
text: notificationText,
trigger: {at: new Date(new Date(DateWithTime).getTime() - 7200)}, // 2 hours before meetup
led: 'FF0000',
vibrate: true,
icon: 'assets/imgs/logo.jpg',
sound: null
});
});
}
我可以将日期转换成图章,但无法计算 一种将时间添加到日期中并解析出确切时间的方法 在该日期和时间盖章。
**
任何帮助将不胜感激。
答案 0 :(得分:0)
尝试以下代码。
formatDateWithTime(date,time){
if(date && time){
let splitDate = date.split('-');
let splitTime = time.split(':');
let formattedDate:any;
return formattedDate = new Date(splitDate[ 2 ], splitDate[ 1 ] - 1, splitDate[ 0 ],splitTime[ 0 ], splitTime[ 1 ],
}else{
return 0
}
}
答案 1 :(得分:0)
以下是Date构造函数,它支持您拥有的所有数据:
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])
这里棘手的部分是Date
构造函数不验证的值。
hour = 25
,则仅添加1 day and 1 hour
。需要明确验证:
function combineDateAndTime(dateStr, timeStr) {
let [dt,month,year] = dateStr.split("-").map(t => parseInt(t)); // pattern: dd-mm-yyyy
let [suffix] = timeStr.match(/AM|PM/); // AM/PM
let [hour,min] = timeStr.match(/\d+/g).map(t => parseInt(t)); // hh:mm
if (month <= 0 && month > 12) return null;
if (hour <= 0 && hour > 23) return null;
if (min <= 0 && min > 59) return null;
month -= 1; // monthIndex starts from 0
if (suffix === "AM" && hour === 12) hour = 0;
if (suffix === "PM" && hour !== 12) hour += 12;
return new Date(year, month, dt, hour, min);
}
console.log(combineDateAndTime("18-9-2018", "12:50 AM").toString());
console.log(combineDateAndTime("18-9-2018", "12:50 PM").toString());