【问题标题】:splitting date/time field to separate date and time将日期/时间字段拆分为单独的日期和时间
【发布时间】:2018-04-17 16:53:45
【问题描述】:

我有一个日期/时间字段(即 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。

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

【问题讨论】:

    标签: parsing datetime split datepicker getdate


    【解决方案1】:

    因为日期和时间之间有一个空格,所以可以通过这种方式分别得到日期和时间。

    方法一:分割字符串

    string date_time = "2018-04-24 10:00:00";
    
    string[] words = date_time.Split(' ');//Split string
    string date = words[0];//date = 1st object (before space)
    string time = words[1];//time= 2nd object (after space)
    

    方法二:使用正则表达式

    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】:

      您是否尝试过new Date('2018-04-24 10:00:00'),然后从日期对象中获取月份年份等后记?

      【讨论】:

        猜你喜欢
        • 2018-08-28
        • 1970-01-01
        • 2018-01-14
        • 2021-11-08
        • 1970-01-01
        • 2013-08-29
        • 2016-06-06
        相关资源
        最近更新 更多