How to change date format using jQuery/Javascript?

空扰寡人 提交于 2019-12-10 15:45:43

问题


Today I want to transfrom date into different format using jQuery/Javascript :

$date = '2013-04-01T19:45:11.000Z'
$cool = date('Y-m-d',strtotime($date));

How can I do that (PHP) in jQuery/Javascript ?

Thanks!


回答1:


You need a date in such format for javascript Sun, 01 Sep 13 08:06:57 +0000 So in PHP you need to do something like this

date_default_timezone_set('Australia/Perth');
echo date('D, d M y H:i:s')." +0000";

And you can experiment with jQuery to check it

$.get('dateformat.php', function(data) {
  date = new Date(data);
  console.log(date);  
});

Then you could format a date as you wish

Example for formatting date object on your own:

$.date = function(dateObj) {
    var d = new Date(dateObj);
    var day = d.getDate();
    var month = d.getMonth() + 1;
    var year = d.getFullYear();

    if (month < 10) {
        month = "0" + month;
    }
    return year + "." + month + "." + day;
};

A jquery plugin to help you format a date similar to php

https://github.com/phstc/jquery-dateFormat

You can use it to apply a format like this

$.format.date("2009-12-18 10:54:50.546", "Test: dd/MM/yyyy")

I think that's it.




回答2:


Use the javascript date object.

<script>
  var date = new Date('2013-04-01T19:45:11.000Z');
  var day = date.getDate();
  var month = date.getMonth();
  var year = date.getFullYear();

  document.write(year + '-' + month + '-' + day);
</script>



回答3:


If you're aiming for newer browsers, then you can parse it directly in JavaScript like fujy or LeGrande showed. But when you do, understand that the UTC date you passed will be converted to the local time zone of the browser.

If you want more flexibility, and full browser compatibility, then you should use a library like moment.js.

// Parse it to a moment
var m = moment("2013-04-01T19:45:11.000Z");

// Format it in local time in whatever format you want
var s = m.format("YYYY-MM-DD  HH:mm:ss")

// Or treat it as UTC and then format it
var s = m.utc().format("YYYY-MM-DD  HH:mm:ss")



回答4:


JavaScript is smart enough to accept dates in different format

var d1 = new Date('2013-04-01T19:45:11.000Z');


来源:https://stackoverflow.com/questions/18553936/how-to-change-date-format-using-jquery-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!