I'm trying to merge two separate integers and convert into a 24 hour format hh:mm:ss. Below is my code:
var hr = 5;
var min = 30;
/**convert to hh:mm:ss*****/
var combine_time = new Date(hr + ":" + min + ":" + "00");
alert(combine_arrive);
However, my javascript show it as invalid date. Can anyone guide me? Thank you
Perhaps you meant this?
We cannot know if 5 is 5am (05) or pm (17) unless you tell us
const arrive_hr = 5;
const arrive_min = 30;
const pad = num => ("0"+num).slice(-2);
const combine_time = `${pad(arrive_hr)}:${pad(arrive_min)}:00`;
console.log(combine_time)
var hr = 5;
var min = 30;
var timeString = `${hr}:${min}:00`
var combine_time = Date.parse('1970-01-01 ' + timeString);
alert(combine_time);
Take a look at the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Use the setter functions.
var hr = 5;
var min = 30;
var combine_time = new Date(); // create new Date and assign value
// as follows you set hr, min and secs
combine_time.setHours(hr);
combine_time.setMinutes(min);
combine_time.setSeconds(0);
Related
I'm trying to set a const "Yesterday" but the script is not recognised as a function (I'm using Google App Scripts).
I've tried different syntax including:
const yesterday = today.setDate(-1);
and
const yesterday = new Date(today.setDate(-1));
But neither worked.
I'm pretty sure it should be a minor change but I cannot figure out how to solve this.
A little help would be highly appreciated, thanks !
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName('My Report');
function insertColumn() {
const range = sheet.getRange('H1:H69').getValues();
const newrange = sheet.getRange('I1:I69');
const rules = sheet.getConditionalFormatRules();
const today = Utilities.formatDate(new Date(), "GMT+7", "MM/dd/yyyy");
const yesterday = new Date(today.setDate(-1));
Your issue is that today is not a Date object, because you've called Utilities.formatDate on it. This is why you are getting an error when trying to use today.setDate(). So you need to use another variable to allow you to compute yesterday. For example:
const tmp = new Date();
const yesterday = new Date(tmp.setDate(tmp.getDate()-1))
Also note that setDate(-1) sets the date to the penultimate day in the previous month (e.g. March 30 when you are in April), you need to get the current date (using getDate) and subtract 1 from that to get yesterday's date.
getYesterday() {
let date = new Date();
let yesterday_milliseconds = date.getTime() - 1000 * 60 * 60 * 24;
let yesterday = new Date();
yesterday.setTime(yesterday_milliseconds);
let strYear = yesterday.getFullYear();
let strDay = yesterday.getDate();
let strMonth = yesterday.getMonth() + 1;
if (strMonth < 10) {
strMonth = "0" + strMonth;
}
if (strDay < 10) {
strDay = "0" + strDay;
}
return strYear + "-" + strMonth + "-" + strDay;
},
function yesterday() {
let dt = new Date();
Logger.log(new Date(dt.setDate(dt.getDate() - 1)));
}
From MDN setDate() returns: The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date... not a date object
i have a date string from an API that looks like this 10:00 and i need add a 1 and a half, i tried with this but it doesn´t work
moment('10:00').add(90, 'minute')
i expect this output 11:30
let time = "10:00"
const add=(minutes)=>{
let [hr, min] = time.split(":")
minutes += parseInt(hr)*60 + parseInt(min)
hr = Math.floor(minutes/60)
min = minutes %60
//console.log(hr%12+":"+ min)
return (hr%12+":"+ min)
}
console.log(add(90))
See comments inline:
let input = "10:00";
let inputParts = input.split(":"); // Split the string at the colon
let d = new Date(); // Create new date
d.setUTCHours(+inputParts[0] + 1); // Get first part of string and add 1
d.setUTCMinutes(30); // Adjust by 1.5 minutes
// Output in the format you want
console.log(d.getUTCHours() + ":" + d.getUTCMinutes());
I need to get the duration between two dates in hh:mm:ss format using moment. but i am not able to get the exact difference. Here is my example.
let start = moment("2018-07-27T14:56:33.763Z");
let end = moment("2018-07-28T14:56:33.763Z");
let diff = end.diff(start);
let f = moment.utc(diff).format("HH:mm:ss");
alert(f);
For the above dates i need to get the output as 24:00:00, because it's one day difference. But i am getting 00:00:00 as response.
If i am changing the hrs it should display based on that. how can i achieve this? can someone help me to fix this.
There's a rather lengthy discussion on Moments GitHub Page but this may be what you are after:
let start = moment("2018-07-27T14:56:33.763Z");
let end = moment("2018-07-28T14:56:33.763Z");
let duration = moment.duration(end.diff(start));
let f = Math.floor(duration.asHours()) + moment.utc(duration.asMilliseconds()).format(":mm:ss")
alert(f);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
By the way there is a plugin that someone created for this specific issue, which is posted on Moments Website as well.
try this:
let f = moment.utc(diff).format('D[days] H[ hours]');
Example
If you want to convert that time in only HH:mm:ss maybe you can manually convert it to miliseconds and parse it to hours.
Try the following to achieve the quest.
let start = moment("2018-07-27T14:56:33.763Z");
let end = moment("2018-07-28T14:56:33.763Z");
let diff = end.diff(start);
var d = moment.duration(diff, 'milliseconds');
var hours = Math.floor(d.asHours());
var mins = Math.floor(d.asMinutes()) - hours * 60;
var secs = Math.floor(d.asSeconds()) - mins * 60 - hours * 60*60;;
console.log( hours + ":" + mins + ":" + secs);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
It states
enter code here
H, HH 24 hour time
h, or hh 12 hour time (use in conjunction with a or A)
Thus, stating your time as HH will give you 24h format, and hh will give 12h format.
Since the difference is a day so hours,minutes,seconds return zero so change the condition in this way
let f = moment.utc(diff).format("HH:mm:ss");
if(f=="00:00:00"){
f=moment.utc(diff).format("D[days] H[hours]");
}
What you are doing is trying to format a difference of 2 dates which will result in a date formated string, what you need to do is to get the difference in hours of both dates, to do that, you need the duration method:
let start = moment("2018-07-27T14:56:33.763Z");
let end = moment("2018-07-28T13:56:33.763Z");
let diff = end.diff(start);
let diffData = moment.duration(diff);
alert((diffData.days() * 24) + diffData.hours());
This will help you.
var units = ["year", "month", "day", "hour", "minute", "second", "millisecond"];
var unitmapping = {month:12,day:30,hour:24,minute:60,second:60,millisecond:1000};
function getDiff(start, end)
{
var duration = "", start = moment(start), end = moment(end);
units.forEach(function(unit,index){
var diff = Math.abs(end.diff(start,unit));
if(unitmapping[unit]) diff = (diff%unitmapping[unit]).toFixed(0);
duration += diff + " "
+ unit
+ (diff==1 ? "":"s")
+ (index!=units.length-1 ? " : ":"");
});
return duration;
}
console.log(getDiff("2018-07-27T14:56:33.843Z","2018-07-27T14:56:33.763Z"));
console.log(getDiff("2018-07-26T14:56:33.843Z","2018-07-27T14:56:33.763Z"));
console.log(getDiff("2018-07-27T14:46:33.843Z","2018-07-27T14:56:33.763Z"));
console.log(getDiff("2018-07-27T14:56:33.843Z","2048-07-29T14:56:33.763Z"));
console.log(getDiff("2018-09-27T14:56:33.843Z","2048-07-29T14:56:33.763Z"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
I have two times, say timeS = '00.00.00' and timeE = '10.00.00'
I want to get the time difference between the two times. One way is the following manner,
//create date format
var timeStart = new Date("01/01/2007 " + timeS).getHours();
var timeEnd = new Date("01/01/2007 " + timeE).getHours();
var hourDiff = timeEnd - timeStart;
Here, I had to get the desired result using the Date format. Is there any other way to achieve this, without explicitly making a Date object?
Note: Instead of marking it a duplicate, do observe that I am asking for some other alternative ways.
Convert the hh.mm.ss format into equivalent seconds by parsing.
var timeS = '00.00.00';
var timeE = '10.00.00';
function convertToSeconds(timeString) {
var timeSplit = timeString.split('.');
return timeSplit.reduce((result, item, index) => {
return result + Number(item) * Math.pow(60, timeSplit.length - index - 1)
}, 0);
}
const secondDifference = convertToSeconds(timeE) - convertToSeconds(timeS);
console.log(secondDifference);
You need to convert this time to a Date first
var convertToMS = time => {
var d = new Date(1,1,1);
d.setHours.apply( d, time.split(".").map( Number ) );
return d.getTime();
};
var diffOutput = convertToMS( timeE ) - convertToMS( timeS );
Demo
var convertToMS = time => {
var d = new Date();
d.setHours.apply(d, time.split(".").map(Number));
return d.getTime();
};
var timeS = '00.00.00';
var timeE = '10.00.00';
var diffOutput = convertToMS(timeE) - convertToMS(timeS);
console.log(diffOutput)
Edit
As suggested by #RobG, check this alternate solution using UTC
var convertToMS = time => Date.UTC(1,1,1, ...time.split('.'));
I need to create a new date/time string based on some variabeles. But I'm not sure how I could do this, I've been searching a bit but can't really find a solution.
var fields = 5; //Fields can vary from 1 tot 999;
var currenttime = $("#serverTime").text().split(":"); //format: 23:02:59
var timetoadd = 5*30 // 150 minutes
var totalseconds = currenttime[0]*3600 + currenttime[1]*60 + currenttime[2] + timetoadd*60;
var currentdate = new Date();
Any help would be much appreciated.
Type cast it:
var totalseconds = parseInt(currenttime[0])*3600 + parseInt(currenttime[1])*60 + parseInt(currenttime[2]) + timetoadd*60;
To get new date:
var t = new Date(1970,0,1);
console.log(t.setSeconds(totalseconds));