日期格式?

时间:2010-10-26 03:28:33

标签: javascript datetime

我正在使用带有json端点的api来获取一些数据。

api返回的日期如下:Date(1288205847730)(所以基本的javascript日期对象)

如何将其转换为Thu, 28 Oct

<小时/> 这是我可以解决的普遍问题。

实际问题是,如果从现在到该日期之间的时间超过24小时,我想显示Thu, 28 Oct格式,

如果我想要显示13 hours 8 minutes

(注意:使用的时间是弥补的,与使用的时间不对应)

5 个答案:

答案 0 :(得分:0)

这是一个标准的UNIX时间戳,以毫秒为单位,因此JavaScript可以直接处理它:

var timestamp = 1288205847730;
var dateTime = new Date(timestamp); // => Wed Oct 27 2010 13:57:27 GMT-0500 (Central Daylight Time)

至于格式化,我建议使用别人的代码,因为那里已经有很多了。这是一个Google search让你入门;前几个结果应该让你开始。

答案 1 :(得分:0)

JavaScript的每个实现都可能有所不同。我在Working with Dates上推荐这篇文章。它描述了将日期格式化为字符串的功能。

示例:

var current_date = new Date ( );

var month_names = new Array ( );
month_names[month_names.length] = "January";
month_names[month_names.length] = "February";
month_names[month_names.length] = "March";
month_names[month_names.length] = "April";
month_names[month_names.length] = "May";
month_names[month_names.length] = "June";
month_names[month_names.length] = "July";
month_names[month_names.length] = "August";
month_names[month_names.length] = "September";
month_names[month_names.length] = "October";
month_names[month_names.length] = "November";
month_names[month_names.length] = "December";

var day_names = new Array ( );
day_names[day_names.length] = "Sunday";
day_names[day_names.length] = "Monday";
day_names[day_names.length] = "Tuesday";
day_names[day_names.length] = "Wednesday";
day_names[day_names.length] = "Thursday";
day_names[day_names.length] = "Friday";
day_names[day_names.length] = "Saturday";

document.write ( day_names[current_date.getDay()] );
document.write ( ", " );
document.write ( month_names[current_date.getMonth()] );
document.write ( " " + current_date.getDate() );
document.write ( " " );
document.write ( " " + current_date.getFullYear() );

答案 2 :(得分:0)

你可以做的最好的事情就是用普通的javascript自己构建整个字符串

Date d = new Date(1288205847730); // milliseconds
d.toLocaleDateString(); 

如果您想使用像jQuery这样的库,您可以找到执行此操作的插件:http://plugins.jquery.com/project/jquery-dateFormat

答案 3 :(得分:0)

是的,遗憾的是没有像php那样体面的内置日期方法。如果没有使用可能过度杀戮的库,你必须创建自己的格式化功能。 Jordons在正确的轨道上,但请不要初始化你的阵列,就像他使用下面的

month_names = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November","December"];

以下是可用日期函数的列表 http://www.w3schools.com/jsref/jsref_obj_date.asp

答案 4 :(得分:0)

从我的工具箱中找到了这个。您可以根据您的规范修改日期obj的原型。

<script type="text/javascript" language="javascript">
Date.prototype.toDayDateMonth = function(){
    var dayname = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
    var monthname = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    return ( dayname[this.getDay()] + " " + this.getDate() + " " + monthname[this.getMonth()] )
}

var d1 = new Date(1288205847730);
alert(d1.toDayDateMonth());
</script>