Reputation: 3359
If I receive all records from DB with JSON how I can change format 2014-09-04 23:20:00
(this is stored on DB) to 04/09/2014
. At the moment date are parsed to 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>
Upvotes: 1
Views: 172
Reputation: 2729
// 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)
Upvotes: 0
Reputation: 723
You can extract the day, month and year from your Date and then use it to form a string. You can try something as the following:
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);
where jsonDate is the date element you extracted from JSON.
Upvotes: 1
Reputation: 3253
If you got the values as Thu Jan 01 1970 00:00:02 GMT+0000 (GMT Standard Time) means, then do like following
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()
So you'll get the day, month and year. You can format as the way you want.
Upvotes: 1
Reputation: 1073968
You parse the string, using any of several libraries available for the purpose, and then put it in the format you want, using any of several libraries avaialble for the purpose. On a modern browser, the string you've quoted should be parsed correctly by new Date()
, but if you're seeing it not get parsed correctly (your example makes no sense), you may need something like MomentJS.
Or of course, you can regex it:
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>
Upvotes: 1