Date.parse(2/4/2011 9:34:48 AM)

后端 未结 3 586
北荒
北荒 2021-01-24 05:30

my input will be from a variable (Ticket.CreationDate) and will look like

2/4/2011 9:34:48 AM (it will vary of course)

Ideally I could pass in the variable as-i

相关标签:
3条回答
  • 2021-01-24 05:58

    Create a function which takes date and in-format string and out-format string as parameter

    string FormatDate(string date, string informat,string outformat)
    {
        var culture = CultureInfo.CreateSpecificCulture("en-US");
        return DateTime.ParseExact(date, informat, culture).ToString(outformat);
    }
    
    FormatDate("2/4/2011 9:34:48 AM","M/d/yyyy H:m:s tt","H:m:s")               //9:34:48
    

    You can get different format string from here

    0 讨论(0)
  • 2021-01-24 06:22

    I would suggest a combination of 2 different Date libraries I am aware of.

    The first, for parsing the date from a string, is DateJS. You can find it at http://www.datejs.com/. Your example parses with their library fine (once you include appropriate quote marks)

    // Results in Date object whose toString is:  
    //    Fri Feb 04 2011 09:34:48 GMT-0600 (Central Standard Time)
    Date.parse('2/4/2011 9:34:48 AM')
    

    The other library is for creating nicely formatted string values based on your date object. This can be found at http://blog.stevenlevithan.com/archives/date-time-format. For example, from that page:

    // Saturday, June 9th, 2007, 5:46:21 PM
    var now = new Date();
    dateFormat(now, "ffffdd, mmmm dS, yyyy, h:MM:ss TT");
    
    0 讨论(0)
  • 2021-01-24 06:23

    The fact that you have a static format makes a solution simple.

    var dateReg = 
        /(\d{1,2})\/(\d{1,2})\/(\d{4})\s*(\d{1,2}):(\d{2}):(\d{2})\s*(AM|PM)/;
    function parseDate(input) {
        var year, month, day, hour, minute, second,
            result = dateReg.exec(input);
        if (result) {
            year = +result[3];
            month = +result[1]-1; //added -1 to correct for the zero-based months
            day = +result[2];
            hour = +result[4];
            minute = +result[5];
            second = +result[6];
            if (result[7] === 'PM' && hour !== 12) {
                hour += 12;
            }       
        }
        return new Date(year, month, day, hour, minute, second);
    }
    
    0 讨论(0)
提交回复
热议问题