我试图以这种格式获取两个日期之间日期差异的详细信息
var strg = '{"name1":123,"name2":123,"name3":123}';
var obj = JSON.parse(strg);
for (var i in obj){
obj[i] = String(obj[i])
}
console.log(obj)
到目前为止这是我的代码..目前无效
0 years 2 days 1 hours 20 minutes 47 second
当前输出
<script>
var starting_date = '2017-08-02 08:32:28';
var closing_date= '2017-08-02 09:30:05';
window.onload=function() {
// Month,Day,Year,Hour,Minute,Second
upTime(starting_date); // ****** Change this line!
};
function upTime(countTo) {
//now = new Date();
countTo = new Date(countTo);
//difference = (now-countTo);
difference = (closing_date-countTo);
days=Math.floor(difference/(60*60*1000*24)*1);
years = Math.floor(days / 365);
if (years > 1){ days = days - (years * 365)}
hours=Math.floor((difference%(60*60*1000*24))/(60*60*1000)*1);
mins=Math.floor(((difference%(60*60*1000*24))%(60*60*1000))/(60*1000)*1);
secs=Math.floor((((difference%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1);
document.getElementById('years').firstChild.nodeValue = years;
document.getElementById('days').firstChild.nodeValue = days;
document.getElementById('hours').firstChild.nodeValue = hours;
document.getElementById('minutes').firstChild.nodeValue = mins;
document.getElementById('seconds').firstChild.nodeValue = secs;
clearTimeout(upTime.to);
upTime.to=setTimeout(function(){ upTime(countTo); },1000);
}
</script>
<div id="countup">
It's been
<span id="years">00</span>
<span class="timeRefYears">years</span>
<span id="days">00</span>
<span class="timeRefDays">days</span>
<span id="hours">00</span>
<span class="timeRefHours">hours</span>
<span id="minutes">00</span>
<span class="timeRefMinutes">minutes</span>
<span id="seconds">00</span>
<span class="timeRefSeconds">second</span>
</div>
如果我使用当前日期它可以正常工作
It's been NaN years NaN days NaN hours NaN minutes NaN second
答案 0 :(得分:2)
尝试替换
var starting_date = '2017-08-02 08:32:28';
var closing_date= '2017-08-02 09:30:05';
用这个?
var starting_date = new Date('2017-08-02 08:32:28');
var closing_date= new Date('2017-08-02 09:30:05');
但我建议你在here
中讨论一个时区但如果您只是想减轻操纵日期的麻烦,请尝试使用moment.js
答案 1 :(得分:1)
在您将countTo设置为Date的情况下将closing_date设置为1。也不要使用相同的变量名称:
var starting_date = '2017-08-02 08:32:28';
var closing_dateStr = '2017-08-02 09:30:05'; //append Str
function upTime(countToStr) { //append Str
//now = new Date();
var countTo = new Date(countToStr);
var closing_date = new Date(closing_dateStr);
我的假设是你从某个地方获取字符串日期,你需要转换它们,所以在调用方法之前转换它们并不是你的解决方案。