将日期/时间字段拆分为单独的日期和时间

时间:2018-04-17 16:53:45

标签: parsing datetime split datepicker getdate

我有一个日期/时间字段(即2018-04-24 10:00:00),我想分成不同的日期和时间。我有以下功能,但它不适用于uib-datepicker,因为我将字符串分割为日期/时间字段:

function returnDate(date) {
    var apptDate = date.split(' ')[0];
    return apptDate;
}

function returnTime(date) {
    var apptTime = date.split(' ')[1].substring(0,5);
    var hours24 = parseInt(apptTime.substring(0, 2),10);
    var hours = ((hours24 + 11) % 12) + 1;
    var amPm = hours24 > 11 ? 'pm' : 'am';
    var minutes = apptTime.substring(2);
    return hours + minutes + ' ' + amPm;
}

我还尝试过使用getDate,getFullYear,getMonth等,但我一直在使用getDate获取TypeError。

有人可以就此日期问题提供一些指导吗?谢谢!

2 个答案:

答案 0 :(得分:0)

您是否尝试了new Date('2018-04-24 10:00:00')然后根据日期对象设置了月份等等?

答案 1 :(得分:0)

因为日期和时间之间有空格,所以你可以通过这种方式单独获得日期和时间。

方法1:拆分字符串

string date_time = "2018-04-24 10:00:00";               
string _date = "";    
string _time = "";

Regex date = new Regex(@"([0-9-]+)\s");            
Match match_date = date.Match(date_time);

Regex time = new Regex(@"\s([0-9:]+)");
Match match_time = time.Match(date_time);

//Date
if (match_date.Success)
{
    _date =  match_date.Value;
    Console.WriteLine(_date);
}
//Time
if (match_time.Success)
{
    _time = match_time.Value.Replace(" ","");
    Console.WriteLine(_time);
}

方法2:使用正则表达式

{{1}}
相关问题