将 JSON 日期解析为另一种格式

parse JSON date to another format

本文关键字:另一种 格式 JSON 日期      更新时间:2023-09-26

如果我使用 JSON 从数据库接收所有记录,我如何将格式2014-09-04 23:20:00(存储在数据库中)更改为04/09/2014。目前日期被解析为Thu Jan 01 1970 00:00:02 GMT+0000 (GMT Standard Time)

<script> 
$("document").ready(function() {
    $.getJSON("test1.php", function(data) {
        var table = $("<table>");
        $("#div-my-table").empty().append(table);
        $.each(data, function(i, item) {
            table.append("<tr><td>" + item.code +"</td><td>" + item.line +"</td><td>" + item.org +"</td><td>" + new Date(parseInt(item.by_date.substr("u"))) + "</td></tr>");
        });
    });
});        
</script>

您可以使用可用于此目的的多个库中的任何一个来分析字符串,然后使用可用于该目的的多个库中的任何一个将其放入所需的格式。在现代浏览器上,你引用的字符串应该被new Date()正确解析,但如果你看到它没有被正确解析(你的示例没有意义),你可能需要像 MomentJS 这样的东西。

或者,当然,您可以正则表达式:

var yourString = "2014-09-04 23:20:00";
var parts = /^('d{4})-('d{2})-('d{2})/.exec(yourString);
var newString = parts[3] + "/" + parts[2] + "/" + parts[1];
snippet.log("newString = " + newString);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

如果您得到的值为 1970 年 1 月 1 日星期四 00:00:02 GMT+0000(GMT 标准时间)的意思,那么请像下面这样

 var d=new Date('Thu Jan 01 1970 00:00:02 GMT+0000 (GMT Standard Time)');
    var day=d.getDate();
    var month=d.getMonth()+1;
    var year = d.getFullYear();
then format the string like d.getDate()+"/"+(d.getMonth()+1)+"/"+d.getYear()

所以你会得到日、月和年。您可以根据需要进行格式设置。

您可以从日期中提取日,月和年,然后使用它来形成字符串。您可以尝试以下操作:

var dateObj = new Date(jsonDate);
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
newdate = day + "/" + month + "/" + year;
alert(newdate);

其中 jsonDate 是从 JSON 中提取的日期元素。

// Split timestamp into [ Y, M, D, h, m, s ]
var t = "2010-06-09 13:12:01".split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
alert(d);
// -> Wed Jun 09 2010 13:12:01 GMT+0100 (GMT Daylight Time)