Proper way to format date from database using javascript/jquery

前端 未结 3 1053
礼貌的吻别
礼貌的吻别 2021-01-17 06:11

I am calling my database which contains a datetime datatype. The date looks like this:

2005-05-23 16:06:00.000

I would like to display this in a table when a

3条回答
  •  感动是毒
    2021-01-17 06:27

    The date you're getting back is serialized to a marker and a number of milliseconds since midnight 1st Jan 1970 (in UTC). If you isolate the numeric portion, convert it into a number, and feed it into the Date constructor you'll get an actual date to work with, which you can then format as you like.

    var ticks, dt;
    
    // Isolate the numeric portion of the value
    ticks = /[0-9]+/.exec(json.dateValue)[0];
    
    // Convert to a number
    ticks = parseInt(ticks);
    
    // Convert to a date
    dt = new Date(ticks);
    

    Alternately, if the JSON serializer on the server supports a "replacer" parameter as Crockford's and ECMAScript 5th edition's do, you could supply a replacer that formatted the date into a string server-side and handle it there, since you said you don't want to parse the date client-side (although the jQuery tag suggested to me maybe you did).

提交回复
热议问题