Momentjs seconds from now - javascript

var startdate = '02.05.2018 18:05:03';
How to find out how many minutes have passed from startdate to now?
My try
var exp = moment(startdate);
minutes = moment().diff(exp, 'minutes');
but result 124764 it not right

Parsing of date strings are not consistent among browsers. Always pass the format of the string if it is in non-ISO format to prevent unwanted bugs:
var exp = moment(startdate, 'DD.MM.YYYY HH:mm:ss');
moment().diff(exp, 'minutes');

To get the difference between two moment time objects, you can use .diff(). Then you can use any of asHours(), asMinutes(), asSeconds() to get human-readable time difference.
var start = moment('02.05.2018 18:05:03');
var end = moment('02.05.2018 18:11:03');
var duration = moment.duration(end.diff(start));
var mins = duration.asMinutes();
console.log(mins)
In your case, you can simply call moment().diff(time) since you want to get difference between the time you specify and now.
var time = moment('02.05.2018 18:05:03');
var duration = moment.duration(moment().diff(time));
var mins = duration.asMinutes();
console.log(mins)

Related

Setting the milliseconds on Timeout based on given date time

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 get a string date in the format "2016-07-06T10:57Z" from Date() and toISOString

I need to get a date in this format:
2016-07-06T10:57Z
Using this code I have been able to get a date in a format somewhat like I need:
var isoDate = new Date().toISOString();
2016-07-06T08:46:08.127Z
But is there a way I can remove the seconds and fraction of seconds from the date so it appears exactly like the date: "2016-07-06T10:57Z" ?
You will always want to remove the last 8 characters ('Z' included) thus you can use a function like slice
isoDate = isoDate.slice(0, -8); //Remove seconds + fractions + Z
isoDate += "Z"; //Add back the Z
You can use this way because the format returned by toISOString() will always be
YYYY-MM-DDTHH:mm:ss.sssZ
Please try
var isoDate = new Date().toISOString();
var pos = isoDate.lastIndexOf(':');
var datePart1 = isoDate.substring(0,pos);
var datePart2 = isoDate.substr(-1, 1);
var dateStr = datePart1+datePart2;
console.log(dateStr);

How to find the number of days difference using Google Script

I was trying to find the difference between two days, I'm getting NaN.
function formatDate(oldFormat,duration,timestamp){
var formattedDate = Utilities.formatDate(oldFormat, "IST","yyyy,MM,dd");
Logger.log(timestamp);
var newDate=new Date(timestamp*1000);
Logger.log(newDate);
newDate=Utilities.formatDate(newDate,"IST","yyyy,MM,dd");
Logger.log(formattedDate);
Logger.log(newDate);
var date1=new Date(formattedDate).getTime();
Logger.log(date1)
var date2=new Date(newDate).getTime();
Logger.log(date2)
var diff=daydiff(date2,date1);
Logger.log(diff); }
function daydiff(first, second) {
return (second-first)/(1000*60*60*24);}
How to find the difference between two date in days? I've date in this format :
date 1 : 2015,05,12
date 2: 2015,05,28
There is no point to use Utilities.formatDate() as it is meant to convert a normal date in to any format, not the other way round.
Also not sure what (oldFormat,duration,timestamp) stand for. You do not use duration in your script, and both dates you showed seem to be the same format.
If you are simply trying to find the difference between two dates, try this:
function formatDate(date1,date2){
date1 = new Date(fixDate(date1));
date2 = new Date(fixDate(date2));
var diff = (date2-date1)/(1000*60*60*24);
return(diff);
}
function fixDate(date){
var collector = date;
if (collector.match(",")!=null){
collector = collector.split(",");
var myString = [collector[1], collector[2], collector[0]].join("/");
return myString
}
}

How do I get the time in milliseconds from 2 different string?

I have the following code which I get from parameters in the URL.
This is what I have in the URL
&dateStart=15.01.2015&timeStart=08%3A00&
After getting the parameters I have the following: 15.01.2015:08:00
Using Javascript how can I parse this string to get the date in milliseconds?
Date.parse(15.01.2015:08:00)
But obviously this doesn't work.
Date.parse(15-01-2015)
This works and I can change this but then how do I add or get the milliseconds from the time??
This is quite possibly the ugliest JavaScript function I've written in my life but it should work for you.
function millisecondsFromMyDateTime(dateTime) {
var dayMonth = dateTime.split('.');
var yearHourMinute = dayMonth[2].split(':');
var year = yearHourMinute[0];
var month = parseInt(dayMonth[1]) - 1;
var day = dayMonth[0];
var hour = yearHourMinute[1];
var minute = yearHourMinute[2];
var dateTimeObj = new Date(year, month, day, hour, minute, 0, 0);
return dateTimeObj.getTime();
}
It will work with the format that your DateTime is in aka day.month.year:hours:minutes.
You can achieve it using Javascript Date Object and JavaScript getTime() Method:
var dateString="01.15.2015 08:00";
var d = new Date(dateString);
console.log(d);
var ms=d.getTime();
console.log(ms);
ms+=10000;
console.log(new Date(ms));
Here is a DEMO Fiddle.
Note: Change your date string from 15.01.2015:08:00 to "01.15.2015 08:00" because it's not a valid Date format.
Check for format
Date() in javascript :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Format allowed :
https://www.rfc-editor.org/rfc/rfc2822#page-14
You can try to use moment.js library like this:
moment('15.01.2015 08:00', 'DD.MM.YYYY HH:mm').milliseconds()
Just for the sake of completion, you can always extract the information and create a Date object from the extracted data.
var dateStart = '15.01.2015'
var timeStart = '08:00';
var year = dateStart.substring(6,10);
var month = dateStart.substring(3,5);
var day = dateStart.substring(0,2);
var hour = timeStart.substring(0,2);
var mins = timeStart.substring(3,5);
var fulldate = new Date(year, month-1, day, hour, mins);
console.log(fulldate.getTime());

Convert UTC time to specific zone

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 :).

Categories