I'm creating a function to compare a custom date-time with current date-time.
I convert a string dd/MM/yyyy HH:mm:ss
to new Date()
before comparing.
Here is the code:
var getCurrentDateTime = function () {
var dt = new Date(),
dd = dt.getDate(),
MM = dt.getMonth() + 1,
yyyy = dt.getFullYear(),
HH = dt.getHours(),
mm = dt.getMinutes(),
ss = dt.getSeconds();
return new Date(yyyy, MM, dd, HH, mm, ss)
};
var parseTimeString = function (d) {
// `d` formatting: 'dd/MM/yyyy HH:mm:ss'
var d_d = d.split(' ')[0],
d_t = d.split(' ')[1],
//x = new Date(2016, 01, 14, 21, 40, 00),
x = new Date(+d_d.split('/')[2], +d_d.split('/')[1] - 1,
+d_d.split('/')[0], +d_t.split(':')[0],
+d_t.split(':')[1], +d_t.split(':')[2]),
c = getCurrentDateTime(),
z = Math.abs((c.getTime() - x.getTime())/1000);
if (z <= 29) {
return 'Just now'
}
if (z > 29 && z < 60) {
return '30 seconds ago'
}
if (z >= 60 && z < 120) {
return '1 minute ago'
}
if (z >= 120 && z < 3600) {
return (c.getMinutes() - x.getMinutes()) + ' minutes ago'
}
if (z >= 3600 && z < 7200) {
return '1 hour ago'
}
if (z >= 7200 && z < 86400) {
return (c.getHours() - x.getHours()) + ' hours ago'
}
if (z >= 86400 && z < 172800) {
var m = x.getMinutes();
return 'Yesterday ' + x.getHours() + ':' + (m < 10 ? '0' + m : m)
}
if (z >= 172800) {
var dd = x.getDate(),
MM = x.getMonth() + 1,
yyyy = x.getFullYear(),
m = x.getMinutes();
dd = dd < 10 ? '0' + dd : dd;
MM = MM < 10 ? '0' + MM : MM;
return dd + '/' + MM + '/' + yyyy + ' at ' + x.getHours() + ':' + (m < 10 ? '0' + m : m)
}
};
$('button').click(function () {
setInterval(function () {
var x = parseTimeString('14/01/2016 21:40:00');
$('body').html($('<p>').text(x))
}, 1000)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click me</button>
My problem:
The line
x = new Date(+d_d.split('/')[2], +d_d.split('/')[1] - 1,
+d_d.split('/')[0], +d_t.split(':')[0],
+d_t.split(':')[1], +d_t.split(':')[2])
is not converted to new Date()
correctly. Current date-time is: 2016/01/14 21:40:00
, but it printed 14/01/2016 at 21:40
instead of Just now
To check again, I've replaced that line to
x = new Date(2016, 01, 14, 21, 40, 00)
and it's working perfectly. So, why?
p/s: And my sub-question: Is there any problem if I use more than 20 intervals in the same time? (Does my web page run slowly?)