如何将日期转换为时间

How to convert date into timeago

我正在尝试使用 jquery.timeago.js

将日期字段转换为 "timeago" 格式
$("time.timeago").timeago();

var userSpan = document.createElement("span");
userSpan.setAttribute("class", "text-muted");
userSpan.appendChild(document.createTextNode(message.usernameSender +" | "));
var timeTag = document.createElement("time");
timeTag.setAttribute("class", "timeago");
timeTag.setAttribute("datetime",document.createTextNode(message.date));
userSpan.appendChild(timeTag);

这个javascript会生成下面的代码

<span class="text-muted">user1 | <time class="timeago" datetime="[object Text]"></time></span>

我的问题是 datetime 的结果是 [object Text]

我错过了什么?

谢谢

My problem is that the result of datetime is [object Text]

嗯,是的,因为你告诉 JavaScript 这样做:

timeTag.setAttribute("datetime",document.createTextNode(message.date));

尝试

timeTag.setAttribute("datetime", message.date);

属性值是字符串,而 DOM 节点(包括文本节点)是对象。