I can't seem to figure out how to properly subtract two times that I've formatted using this line of code:
var moment = require('moment');
var moment = require('moment-timezone');
moment();
moment().tz("America/New_York");
clockedIn = moment().tz("America/New_York").format('HH:mm A');
clockedOut = moment().tz("America/New_York").format('HH:mm A');
From what I've researched, I can see that using the .format method transforms the time into a string. How would I be able to retain my local time variable and subtract it from another one? I am attempting to build a time punch bot and I have the clockIn/Out routed to an interactive menu with buttons. I am new to this and would appreciate any help/insight.
Not sure if I understood correctly, but just don't format the data until you actually output it.
var clockedIn = moment().tz("America/New_York");
console.log('In: ', clockedIn.format('HH:mm A'));
setTimeout(function() {
var clockedOut = moment().tz("America/New_York");
console.log('Out: ', clockedOut.format('HH:mm A'));
var difference = clockedOut - clockedIn; // milliseconds
console.log('Time (secs): ', difference / 1000);
}, 2000);
Related
I need help with setting my timeout for the function. I'm trying to set the timeout for a given date and time but my conversion of them to milliseconds is not working.
Here's my code. Please help.
<script>
var ref = firebase.database().ref().child("Message");
var newRef = ref.child("20161227125916539")
newRef.on('value',function(snap){
heading.innerText =snap.child("message").val();
});
ref.on("child_added",function(snap){
var date = snap.child("date").val();
var time = snap.child("time").val();
var type = snap.child("type").val();
var venue = snap.child("venue").val();
var route = snap.child("route").val();
var message = snap.child("message").val();
date = date + time;
date = date.getTime();
var now = new Date();
now = now.getTime();
set = date - now;
var explode = function(){
alert("Boom!");
};
setTimeout(explode, 2000);
});
</script>
You need to parse the date using new Date().
As you said, the value of date is "2016-12-27" and the value of time is "15:30", so while concatenating them, you also need an extra space. Something like:
date = date + " " + time;
var someDate = new Date(date);
var now = new Date();
var diffInMillis = now - someDate
var explode = function(){
alert ("Boom!");
}
setTimeout(explode, diffInMillis);
dateobj=new Date(datestring);
timeinmilliseconds=dateobj.getTime();
//by the way, may check the browsers console if sth is not working:
datestring.getTime();// error:undefined function
Youre calling the getTime function on a string. You need to convert it into a time obj first. Be aware of the right String format. There are good resources online.
The better Way:
A timeout is killed when the browser is reloaded. Thats bad. It would be better to store the time, and regularily check if the time is reached. That would survive reloads, crashes, shutdowns etc:
function set(timestring){
localStorage.setItem("timer",new Date(timestring).getTime());//store timer
check();//start checking
}
function check(){
if(var await=localStorage.getItem("timer")){//if timer is set
var now=new Date().getTime()
if(await<=now){//time reached, or reached in the past
alert("Yay, timer finished");
}else{//not reached yet
console.log(await-now+" left");//log the time left
setTimeout(check,1000);//check again in a scond
}}
window.onload=check;// browser started, check for an existing timer
Use like this:
set("28-12-2016 12:30");
How can I convert seconds to HH:mm:ss?
At the moment I am using the function below
render: function (data){
return new Date(data*1000).toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");;
}
This works on chrome but in firefox for 12 seconds I get 01:00:12
I would like to use moment.js for cross browser compatibility
I tried this but does not work
render: function (data){
return moment(data).format('HH:mm:ss');
}
What am I doing wrong?
EDIT
I managed to find a solution without moment.js which is as follow
return (new Date(data * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
Still curious on how I can do it in moment.js
This is similar to the answer mplungjan referenced from another post, but more concise:
const secs = 456;
const formatted = moment.utc(secs*1000).format('HH:mm:ss');
document.write(formatted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
It suffers from the same caveats, e.g. if seconds exceed one day (86400), you'll not get what you expect.
From this post I would try this to avoid leap issues
moment("2015-01-01").startOf('day')
.seconds(s)
.format('H:mm:ss');
I did not run jsPerf, but I would think this is faster than creating new date objects a million times
function pad(num) {
return ("0"+num).slice(-2);
}
function hhmmss(secs) {
var minutes = Math.floor(secs / 60);
secs = secs%60;
var hours = Math.floor(minutes/60)
minutes = minutes%60;
return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
// return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}
function pad(num) {
return ("0"+num).slice(-2);
}
function hhmmss(secs) {
var minutes = Math.floor(secs / 60);
secs = secs%60;
var hours = Math.floor(minutes/60)
minutes = minutes%60;
return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
// return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}
for (var i=60;i<=60*60*5;i++) {
document.write(hhmmss(i)+'<br/>');
}
/*
function show(s) {
var d = new Date();
var d1 = new Date(d.getTime()+s*1000);
var hms = hhmmss(s);
return (s+"s = "+ hms + " - "+ Math.floor((d1-d)/1000)+"\n"+d.toString().split("GMT")[0]+"\n"+d1.toString().split("GMT")[0]);
}
*/
You can use moment-duration-format plugin:
var seconds = 3820;
var duration = moment.duration(seconds, 'seconds');
var formatted = duration.format("hh:mm:ss");
console.log(formatted); // 01:03:40
<!-- Moment.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<!-- moment-duration-format plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
See also this Fiddle
Upd: To avoid trimming for values less than 60-sec use { trim: false }:
var formatted = duration.format("hh:mm:ss", { trim: false }); // "00:00:05"
var seconds = 2000 ; // or "2000"
seconds = parseInt(seconds) //because moment js dont know to handle number in string format
var format = Math.floor(moment.duration(seconds,'seconds').asHours()) + ':' + moment.duration(seconds,'seconds').minutes() + ':' + moment.duration(seconds,'seconds').seconds();
My solution for changing seconds (number) to string format (for example: 'mm:ss'):
const formattedSeconds = moment().startOf('day').seconds(S).format('mm:ss');
Write your seconds instead 'S' in example.
And just use the 'formattedSeconds' where you need.
In a better way to utiliza moments.js; you can convert the number of seconds to human-readable words like ( a few seconds, 2 minutes, an hour).
Example below should convert 30 seconds to "a few seconds"
moment.duration({"seconds": 30}).humanize()
Other useful features: "minutes", "hours"
The above examples may work for someone but none did for me, so I figure out a much simpler approach
var formatted = moment.utc(seconds*1000).format("mm:ss");
console.log(formatted);
Until 24 hrs.
As Duration.format is deprecated, with moment#2.23.0
const seconds = 123;
moment.utc(moment.duration(seconds,'seconds').as('milliseconds')).format('HH:mm:ss');
How to correctly use moment.js durations?
|
Use moment.duration() in codes
First, you need to import moment and moment-duration-format.
import moment from 'moment';
import 'moment-duration-format';
Then, use duration function. Let us apply the above example: 28800 = 8 am.
moment.duration(28800, "seconds").format("h:mm a");
🎉Well, you do not have above type error. 🤔Do you get a right value 8:00 am ? No…, the value you get is 8:00 a. Moment.js format is not working as it is supposed to.
💡The solution is to transform seconds to milliseconds and use UTC time.
moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a')
All right we get 8:00 am now. If you want 8 am instead of 8:00 am for integral time, we need to do RegExp
const time = moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a');
time.replace(/:00/g, '')
To display number of days along with hours, mins and seconds, you can do something like this:
const totalSec = 126102;
const remainingMillies= (totalSec % 86400) * 1000;
const formatted = `${Math.floor(totalSec / 86400)} day(s) and ${moment.utc(remainingMillies).format('hh:mm:ss')}`;
console.log(formatted );
will output :
1 day(s) and 11:01:42
In 2022 no need for any new plugin just do this
Literally all you need in 2022 prints out duration in hh:mm:ss from two different date strings
<Moment format='hh:mm:ss' duration={startTime} date={endTime} />
I think there's no need to use 3rd part libray/pluggin to get this task done
when using momentJS version 2.29.4 :
private getFormatedDuration(start: Date, end: Date): string {
// parse 'normal' Date values to momentJS values
const startDate = moment(start);
const endDate = moment(end);
// calculate and convert to momentJS duration
const duration = moment.duration(endDate.diff(startDate));
// retrieve wanted values from duration
const hours = duration.asHours().toString().split('.')[0];
const minutes = duration.minutes();
// voilà ! without using any 3rd library ..
return `${hours} h ${minutes} min`;
}
supports also 24h format
PS : you can test and calculate by yourself using a 'decimal to time' calculator at CalculatorSoup
I am trying to figure out how to get current time in different time zones but below method does not return anything
var timeUpdate = setInterval(function () {
var currentTime = moment().format()
var GMT_current_time = currentTime.tz("Europe/London").format("HH:mm DD MMM");
$("#GMT_display_time").text(GMT_current_time);
}, 1000);
The output of the format function is a string. The tz function works on a moment object.
moment().tz("Europe/London")
Returns current time with format.
moment.tz(moment(), 'Asia/Karachi').format('DD/MM/YYYY HH:mm')
I'm trying to get the current date without the time and store it in a variable, within JavaScript. It needs to be without time as I'm converting it to an epoch date, with which I will use to measure the past 24 hours (if date is within 24 hours then it will be displayed). The problem is that with the added time, it doesn't match as within the last 24 hours.
e.g. it returns the date as the following when converted to epoch: 1408704590485
I want it to be like 1408662000000
I'm not to sure how to do this.
Code - How the current days epoch date is currently being stored -
var epochLoggingFrom;
var epochLoggingTo;
$(document).ready(function () {
epochLoggingFrom = dateToEpoch(new Date());
epochLoggingTo = dateToEpoch(new Date());
}
dateToEpoch function -
function dateToEpoch(thedate) {
return thedate.getTime();
}
Try this:
function dateToEpoch(thedate) {
var time = thedate.getTime();
return time - (time % 86400000);
}
or this:
function dateToEpoch2(thedate) {
return thedate.setHours(0,0,0,0);
}
Example : http://jsfiddle.net/chns490n/1/
Reference: (Number) Date.prototype.setHours(hour, min, sec, millisec)
Try this:
var nowDate = new Date();
var date = nowDate.getFullYear()+'/'+(nowDate.getMonth()+1)+'/'+nowDate.getDate();
Note: Adjust format as you want, like reorder day, month, year, remove '/' and get combined date etc.
or use this:
dateToEpoch(new Date().toLocaleDateString())
I tried using javascript. this method returns the current date in "DD/MM/YYYY" format.
getCurrentDate() {
const t = new Date();
const date = ('0' + t.getDate()).slice(-2);
const month = ('0' + (t.getMonth() + 1)).slice(-2);
const year = t.getFullYear();
return `${date}/${month}/${year}`;
}
I have the following data:
var currentTime: 2013-07-11 15:55:36+00:00
var currentTimezone: Africa/Asmera
I need a way to convert the currentTime in UTC to a new time based on currentTimezone.
I've looked into Timezone.js and I'm having trouble implementing it (the directions on the site are a little ambiguous)
The code for the function I'm intending on using is included. Thanks :)
<script>
$("#storeTime").click(function(){
storeCurrentTime();
})
$("#getTime").click(function(){
retrieveTime();
})
$("#storeTimezone").click(function(){
var yourTimezone = $('#timezone-select').find(":selected").text();
tz = yourTimezone.toString();
storeCurrentTimezone(tz);
})
$("#convertTime").click(function(){
//get the most recent UTC time, clean it up
var currentTime = $('#RetrievedTime').html();
currentTime = currentTime.split(": ")[1];
$('#convertedTime').html("Converted Time: " + currentTime);
//get the saved timezone
var currentTimezone = $('#storedTimezone').html();
})
</script>
You're going to need to know the timezone offset, so some sort of dictionary with strings to numbers.
// assuming your dictionary says 3 hours is the difference just for example.
var timezoneDiff = 3;
Then you can just make a new time like this
// Assuming you have the proper Date string format in your date field.
var currentDate = new Date(currentTime);
// Then just simply make a new date.
var newDate = new Date(currentDate.getTime() + 60 * 1000 * timezoneDiff);
Update
I've written a javascript helper for this which you can find at:
http://heuuuuth.com/projects/OlsonTZConverter.js
I pulled the timezone data from the wikipedia page https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
Usage is as follows once included the script.
var offset = OlsonTZConverter.GetUTCOffset("Africa/Asmera");
or if there is Daylight Savings in effect:
var offset = OlsonTZConverter.GetUTCOffset("Africa/Asmera",true);
These will throw if you pass an invalid timezone, but you can check if a timezone is valid with:
var isValid = OlsonTZConverter.Contains("Africa/Asmera");
or just look at the entire dictionary with:
var tzDict = OlsonTZConverter.ListAllTimezones();
Hope this maybe saves someone some time sometime :).