首页 > 解决方案 > 在 TypeScript 中将日期和时间字符串合并为一个日期

问题描述

我有一个DatePicker和一个Select手动添加时间。

DatePicker 返回:2019 年 2 月 20 日星期三 00:00:00 GMT-0400(大西洋标准时间)

选择返回:上午 7:00

const date = 'Wed Feb 20 2019 00:00:00 GMT-0400 (Atlantic Standard Time)';
const time = '7:00 AM';
console.log(new Date(date + time));

我收到错误:无效日期

我也试过:

    const date = 'Wed Feb 20 2019 00:00:00 GMT-0400 (Atlantic Standard Time)';
    const time = '7:00 AM';

    const yy = new Date(date).getFullYear();
    const mm = new Date(date).getMonth() + 1;
    const dd = new Date(date).getDate();
    const completeDate = new Date(mm + dd + yy + time);


    console.log(yy);
    console.log(mm);
    console.log(dd);
    console.log(completeDate);

如何将它们组合成一个日期以将其保存在数据库中?

标签: angulartypescript

解决方案


尝试以下方法 -

const date = 'Wed Feb 20 2019 00:00:00 GMT-0400 (Atlantic Standard Time)';
const time = '7:00 AM';
const yy = new Date(date).getFullYear();
const mm = new Date(date).getMonth() + 1;    
const dd = new Date(date).getDate();

var interMedDt = new Date(mm + '-' + dd + '-' + yy);
interMedDt.setHours((time.split(' ')[0]).split(':')[0]);
interMedDt.setMinutes((time.split(' ')[0]).split(':')[1]);

推荐阅读