Dynamic Moment.js Difference - javascript

i'm trying to display a difference between dates using moment.js and update it every second. More specificly my age.
I'm using moment.js and a plugin called moment-precise-range.js
I get the difference correctly:
function fecha() {
var m1 = moment('1989-11-29 04:00:00','YYYY-MM-DD HH:mm:ss');
var m2 = moment(moment(),'YYYY-MM-DD HH:mm:ss');
var diff = moment.preciseDiff(m1, m2);
document.write(diff)
}
fecha()
And then, I'm trying to use SetInterval():
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var m1 = moment('1989-11-29 04:00:00','YYYY-MM-DD HH:mm:ss');
var m2 = moment(moment(),'YYYY-MM-DD HH:mm:ss');
var diff = moment.preciseDiff(m1, m2);
document.write(diff)
}
But it doesn't work. (I think it keeps loading the webpage but not sure)
What am I doing wrong? Thanks.

It seems like your code is crashing at
moment.preciseDiff(m1,m2);
Here's a working sample of your code with the regular moment.diff()
$(document).ready(function() {
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var m1 = moment('1989-11-29 04:00:00','YYYY-MM-DD HH:mm:ss');
var m2 = moment(moment(),'YYYY-MM-DD HH:mm:ss');
document.write(m2.diff(m1) + "\n");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

Calculate age in JS given the birth date in "dd/mm/yyyy" format

I am trying to write a function in JavaScript to calculate age.
I wrote a function but it does not give accurate age.
function calculateAge(date) {
var formattedDate = date.split("/")
var birthdateTimeStamp = new Date(formattedDate[2], [1], formattedDate[0])
var currentDate = new Date().getTime();
var difference = currentDate - birthdateTimeStamp;
var currentAge = Math.floor(difference / 31557600000)
// dividing by 1000*60*60*24*365.25
return currentAge
}
I try calculateAge("25/11/1993") and I don't get accurate age. Kindly guide me.
You missed the formattedDate for [1] in the new Date() function, so formattedDate[1] it should be.
function calculateAge(date) {
var formattedDate = date.split("/")
var birthdateTimeStamp = new Date(formattedDate[2], formattedDate[1], formattedDate[0])
var currentDate = new Date().getTime();
var difference = currentDate - birthdateTimeStamp;
var currentAge = Math.floor(difference / 31557600000)
// dividing by 1000*60*60*24*365.25
return currentAge
}
var age = calculateAge('25/11/1993');
console.log('My age is', age);

Get days difference in two dates format (YYYY/MM/DD hh:mm)?

I'm trying to get the diference between 2 dates that look like this:
2018/10/05 13:59
But my issue is with my code, it always retunr NaN.
This is my current code:
var start = '2018/10/05 13:59';
var end = '2018/10/05 17:59';
var converted_start = start.replace("/", "-");
var converted_end = end.replace("/", "-");
// end - start returns difference in milliseconds
var diff = new Date(converted_end - converted_start);
// get days
var days = diff/1000/60/60/24;
alert(days);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I tried to replace the / with - in my code but that didn't fix the issue!
Could someone please advice on this issue?
Thanks in advance.
var start = '2018/10/05 13:59';
var end = '2018/10/05 17:59';
var startDate = Date.parse(start);
var endDate = Date.parse(end);
var diff = new Date(endDate - startDate);
var days = diff/1000/60/60/24;
this works for me
You can use the following to get days difference in two dates format (YYYY/MM/DD hh:mm):
var start = new Date('2018/10/05 13:59');
var end = new Date('2018/10/05 17:59');
// get hours
var hours= (end-start)/3600000;
alert(hours);

Can't format using moment.js

I am trying to format a array of dates using moment.js but I get an error stating
dayOfWeek.format is not a function
I am correctly imported
var startOfWeek = moment().startOf('isoWeek');
var endOfWeek = moment().endOf('isoWeek');
var days = [];
var day = startOfWeek;
while (day <= endOfWeek) {
days.push(day.toDate());
day = day.clone().add(1, 'd');
}
var week = days.map(function(dayOfWeek, i){
console.log(dayOfWeek);
dayOfWeek.format("dddd, DD-MM-YYYY")
});
Your code will fail because dayOfWeek is not moment object.
To check if your variable is moment object use .isMoment:
moment.isMoment(dayOfWeek).
To fix your problem simply replace
dayOfWeek.format("dddd, DD-MM-YYYY")
with
moment(dayOfWeek).format("dddd, DD-MM-YYYY")
You are also missing return statement inside .map function.
Working example:
var startOfWeek = moment().startOf('isoWeek');
var endOfWeek = moment().endOf('isoWeek');
var days = [];
var day = startOfWeek;
while (day <= endOfWeek) {
days.push(day.toDate());
day = day.clone().add(1, 'd');
}
var week = days.map(function(dayOfWeek, i){
return moment(dayOfWeek).format("dddd, DD-MM-YYYY")
});
console.log(week);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
moment().format() function usage is not correct.
Current is:
dayOfWeek.format("dddd, DD-MM-YYYY")
Change to:
moment(dayOfWeek).format("dddd, DD-MM-YYYY")
Check here for more information: https://momentjs.com/docs/#/parsing/string-formats/
dayOfWeek = moment(dayOfWeek).format("dddd, DD-MM-YYYY");
Just a tip, You can also do this
var currentDate = moment(new Date()); // pass your date obj here.
console.log(currentDate.format('DD-MM-YY HH:mm:ss')); // later simply do this.
<script src="https://unpkg.com/moment#2.22.2/min/moment.min.js"></script>

Javascript's date object toLocaleTimeString adds an hour

I'm trying to create a timer from when the user clicks a button.
To do this I tried to calculate the difference between two date objects. When I output the difference, it works. However thetoLocaleTimeString call returns a string with an extra hour added:
var start;
var timer;
function myTimer() {
var current = new Date();
var difference = new Date(current - start);
console.log(difference.getTime(), difference.toLocaleTimeString(navigator.language));
document.getElementById("timer").innerHTML = difference;
document.getElementById("timer2").innerHTML = difference.toLocaleTimeString('en-GB');
}
start = new Date();
timer = setInterval(myTimer, 1000);
draw();
<h1 id="timer"></h1>
<h1 id="timer2"></h1>
What am I doing wrong?
Specify the time zone as UTC in the options argument. Otherwise, the difference date will be adjusted to the user agent's time zone.
document.getElementById("timer2").innerHTML = difference.toLocaleTimeString('en-GB', { timeZone: 'UTC' });
Read more on the options argument and toLocaleTimeString in the MDN documentation.
var start;
var timer;
function myTimer() {
var current = new Date();
var difference = new Date(current - start);
console.log(difference.getTime(), difference.toLocaleTimeString(navigator.language));
document.getElementById("timer").innerHTML = difference;
document.getElementById("timer2").innerHTML = difference.toLocaleTimeString(navigator.language, { timeZone: 'UTC', hour12: false });
}
start = new Date();
timer = setInterval(myTimer, 1000);
draw();
<h1 id="timer"></h1>
<h1 id="timer2"></h1>
Because of the problems with JS and timezones, you are better of using something like moment.js's timezone (http://momentjs.com/timezone/) to do correct conversions (that keep in mind the shift of BST, GMT, differences between countries, etc..). For the purpose of your timer, the following would work as well, and is more accurate as well as simpler to reason about:
// Use Date.now() to get the time in milliseconds for this local computer
var start = Date.now();
var time = new Date();
// This function will prepend a 0 to a number lower than 10
function prependZero(v){
if(v < 9) return '0' + v;
else return v;
}
var timer = setInterval(function() {
// Calculate the difference using the computers local time strings
var difference = new Date(Date.now() - start);
document.getElementById("timer").innerHTML = new Date();
// Now use the Date mnethods to get the correct output:
document.getElementById("timer2").innerHTML = prependZero(difference.getHours()) + ':' + prependZero(difference.getMinutes()) + ':' + prependZero(difference.getSeconds());
}, 1000);
<h1 id="timer"></h1>
<h1 id="timer2"></h1>

setting custom time in flipclock plugin

I am struggling with Flipclock http://flipclockjs.com/ . I browsed their website but i can't find a hint on how to change the time.
What i want to do is set the time i want to display. The problem is the browser on some smart TV's have a problem at changing the timezone so i wanted to get the time from the server with php but i can't set the time. This is my code. I only found some examples with countdown but that is not helpfull at all. It just uses the local time and it doesnt change at all. Thank you all in advance.
// Here i get the unix time from the server in a hidden field
ServerTime = $('#my_time').val();
// FlipClock initialization
clock = $('.clock').FlipClock({
autoStart: false,
clockFace: 'TwentyFourHourClock'
});
var time = clock.getTime();
console.log(time);
clock.setTime(time + 3600);
clock.start();
As i found out that FlipClock plugin somehow doesn't work with setTime() so i changed the code somewhere else. This is my initialization code for generating the FlipClockJS plugin.
var clock;
var index = '';
$(document).ready(function() {
clock = $('.clock').FlipClock({
clockFace: 'TwentyFourHourClock'
});
});
The changes i did was in the file Flipclock.js . It's around the 1325 line. Search for getMilitaryTime
Original:
getMilitaryTime: function() {
var date = new Date();
var obj = this.digitize([
date.getHours(),
date.getMinutes(),
date.getSeconds()
]);
return obj;
},
Edited:
getMilitaryTime: function() {
var date = new Date();
/* The folowing code looks at my server time and if it's higher or smaller it adds so many hours it is missing */
var ServerTime = $('#my_time').val();
var d = new Date();
var n = d.getHours();
var diff = ServerTime - n;
/*****************************************************************/
var obj = this.digitize([
date.getHours()+(diff),
date.getMinutes(),
date.getSeconds()
]);
return obj;
},
// FlipClock initialization
var ServerTime = $('#my_time').val();
var d = new Date();
var n = d.getHours();
var diff = ServerTime - n;
clock = $('.clock').FlipClock(diff,{
clockFace: 'TwentyFourHourClock'
});
This should allow you to display your time without modifications to the source code.
use this 100% work
<script>
var date = new Date('2016-11-07 07:00:0 am');
clock = $('.clock').FlipClock(date, {
clockFace: 'DailyCounter',
countdown: true,
showSeconds: false
});
</script>
you can change the clockFace value as per your requirement.

Categories

Resources