我有一个从SQLServer数据库表中获取的日期时间值:
2016-08-16T17:00:00Z
使用javascript,我想格式化日期如下:
16/08/2016 17:00:00
我使用了以下代码:
$scope.FormatDate = function (value) {
if (value !== null && typeof (value) !== 'undefined') {
var date = new Date(value);
var returnStr = date.getDate() + "/" + date.getMonth() + 1 + "/" + date.getFullYear();
return returnStr;
} else {
return value;
}
}
示例资源的结果是:
17/71/2016
我希望您的帮助能够将输出结果显示为:“16/08/2016 17:00:00”
答案 0 :(得分:3)
如果您只想格式化它,那么您不需要创建一个实际的日期对象,您可以使用正则表达式进行简单的字符串替换以获取各个部分,按照这个简单的演示: / p>
var value = "2016-08-16T17:00:00Z";
console.log(value.replace(/(\d{4})-(\d\d)-(\d\d)T([^Z]+)Z/,"$3/$2/$1 $4"));

在你的职能范围内:
$scope.FormatDate = function (value) {
if (value !== null && typeof (value) !== 'undefined') {
return value.replace(/(\d{4})-(\d\d)-(\d\d)T([^Z]+)Z/,"$3/$2/$1 $4");
} else {
return value;
}
}
答案 1 :(得分:1)
另一种解决方案:
var parsed = Date.parse("2016-08-16T17:00:00Z"),
date = new Date(parsed),
day = date.getUTCDate(),
month = date.getUTCMonth() + 1,
year = date.getUTCFullYear(),
hour = date.getUTCHours(),
minute = date.getUTCMinutes(),
second = date.getUTCSeconds(),
dateStr = "";
day = day < 10 ? "0" + day : day;
month = month < 10 ? "0" + month : month;
hour = hour < 10 ? "0" + hour : hour;
minute = minute < 10 ? "0" + minute : minute;
second = second < 10 ? "0" + second : second;
dateStr = day + "/" + month + "/" + year + " " + hour + ":" + minute + ":" + second;
console.log(dateStr);
已更新:旧代码可能会在不同国家/地区之间发生变化,因为它们具有不同的本地日期/时间格式,因此我已更新以明确格式化。
答案 2 :(得分:0)
试试这个
function formatDate(date)
{
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
minutes = minutes < 10 ? '0'+minutes : minutes;
seconds = seconds < 10 ? '0'+seconds : seconds;
var strTime = hours + ':' + minutes + ':' +seconds ;
return date.getMonth()+1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
答案 3 :(得分:0)
您可以使用此库根据需要格式化日期,并实现某些逻辑。
只需使用功能参数值并使用时刻。
示例:
[10] pry(main)> User.last.store_credit.expire_at
User Load (1.1ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT 1
StoreCredit Load (0.5ms) SELECT "store_credits".* FROM "store_credits" WHERE "store_credits"."user_id" = $1 LIMIT 1 [["user_id", 2]]
=> nil