将单独的日期字符串和时间字符串组合成解析的日期和时间戳



我一直在研究是否在一个单独的字符串中有日期作为

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

我可以将日期转换为邮票,但我无法计算找出一种将时间添加到日期中并解析出确切时间的方法在日期和时间上盖章。

**

任何形式的帮助都将不胜感激。

尝试以下代码。

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
}
}

这是Date构造函数,它支持您拥有的每一个数据:

new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])

这里的关键部分是Date构造函数不验证值。

  • 如果是hour = 25,则只添加1 day and 1 hour。需要显式验证:
  • hour in[0,23],min in[0.59],monthIndex in[0,11](JS使用0-11表示月份(

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

最新更新