few doubts on following on Excel serial to date conversion code - javascript

I have a few doubts about following the code. can anyone please help me to understand the below code?
async function getNewDate(xlSerial) {
// milliseconds since 1899-31-12T00:00:00Z, corresponds to xl serial 0.
let xlSerialOffset = -2209075200000;
let elapsedDays;
// each serial up to 60 corresponds to a valid calendar date.
// serial 60 is 1900-02-29. This date does not exist on the calendar.
// we choose to interpret serial 60 (as well as 61) both as 1900-03-01
// so, if the serial is 61 or over, we have to subtract 1.
if (xlSerial < 61) {
elapsedDays = xlSerial;
}
else {
elapsedDays = xlSerial - 1;
}
// javascript dates ignore leap seconds
// each day corresponds to a fixed number of milliseconds:
// 24 hrs * 60 mins * 60 s * 1000 ms
let millisPerDay = 86400000;
let jsTimestamp = xlSerialOffset + elapsedDays * millisPerDay;
return new Date(jsTimestamp);
}
Here in the code can anyone tell me what is let xlSerialOffset = -2209075200000;
2)why do subtract 1 in second condition conditions?

Related

Check if the time is within the last five minutes

I have a time displayed on my webpage, and im trying to do an action if the time value i have is 5 minutes or older than the current time.
var date1 = new Date(1625807904*1000); // 1625807904 is my date and time
var convert = date1.getDate()+"/"+(date1.getMonth()+1)+"/"+date1.getFullYear()+" "+date1.getHours()+ ":"+ (date1.getMinutes()<10?'0':'') + date1.getMinutes()+ ":"+(date1.getSeconds()<10?'0':'')+date1.getSeconds();
Just my concept
if ( convert < 5minutes or older than the current time){
**** do something ****
}
Thank you for your time !!!
You can subtract two Date in JavaScript. The default value is based on millisecond:
var date = new Date(1625807904*1000);
console.log('diffrences based on milliseconds', Date.now() - date)
console.log('diffrences based on minutes', (Date.now() - date) /(60 * 1000))
if((Date.now() - date) <= (5 * 60 * 1000))
{
console.log("your condition is meeted. Do your ACTION")
}

Why is this function doesn't returns a time for the range specified?

Consider following code,
// Code from https://stackoverflow.com/a/66035934/14659574
const getRandomTime = (offsetHour = 0, rangeInHours = 2) => {
const curTicks = Date.now() + 0 * (offsetHour*60*60*1000);
const addTicks = (Math.random()*rangeInHours)*60*60*1000;
return new Date(curTicks + addTicks);
};
console.log((new Date()));
for(let i=0; i<10;i++) {
console.log( getRandomTime(1, 2+i));
}
It doesn't respect the range instead it returns random time exceeding the range. I want a random time within a range.
For example, Let's say I want a random time that's 2 hours from now but this function gives me values like 5 hours from now.
The code is taken from my previous question. It's looks like the author of the answer is inactive so I decided to make a follow up question.
I have dyscalculia and unable to debug this. I even tried to label the numbers but it not going anywhere.
What's the wrong with this code?
I believe the bug is in this part: Date.now() + 0 * (offsetHour * 60 * 60 * 1000);.
By multiplying the offset hour by zero, you are effectively resetting it to zero and negating the offset.
As a result, it's not possible to change the starting point from UTC.
With 0 * removed from the method, it works as intended:
const getRandomTime = (offsetHour = 0, rangeInHours = 2) => {
// Removed the offending 0 *
const curTicks = Date.now() + (offsetHour * 60 * 60 * 1000);
const addTicks = (Math.random() * rangeInHours) * 60 * 60 * 1000;
return new Date(curTicks + addTicks);
};
// Prints a time between UTC-5 and 1 hour from then.
console.log("Up to one hour from now: ",getRandomTime(-5, 1));
// Prints a time between UTC-5 and 2 hours from then.
console.log("Up to two hours from now: ",getRandomTime(-5, 2));
// Example continues
console.log("Up to three hours from now: ",getRandomTime(-5, 3));
console.log("Up to four hours from now: ",getRandomTime(-5, 4));

How can I convert float number into minutes to be added to the current UTC time with Javascript?

I apologise in advance for being a complete dunce but these are in fact my very first shaky steps into trying to get something done with Javascript and I feel somewhat lost and confused.
I have the following float: 53.93
This decimal value represents minutes and seconds and it comes from multiplying the longitude I get from the web-browser´s Geolocation API times four (x4). I have this value stored in a variable which I want to convert into minutes and seconds so that I can then add it to the current UTC time so that I can get a new HH:MM:SS time on screen with the added difference(current UTC Time + 53 minutes and 93 seconds.)
I understand that I should first convert times into milliseconds in order to be able to calculate the time difference but I'm stuck at converting the float into minutes and seconds (or should I convert it directly into milliseconds?)
Thank you kindly.
JavaScript's Date works in milliseconds, so if you have a number representing minutes (whether or not including fractional minutes), you can convert that to milliseconds by multiplying it by 60 (to get seconds) and 1000 (to get milliseconds), e.g., multiply by 60,000. But, you've said you have the value 13.48 and later in the text of your question you've said "...current UTC Time + 13 minutes and 48 seconds..." Those are two different things. .48 of a minute is roughly 28.79 seconds, not 48 seconds. So if you really mean that the figure 13.48 is supposed to mean 13 minutes and 48 seconds, the calculation is more compliated:
const value = 13.48;
const wholeMinutes = Math.trunc(value);
const milliseconds = (wholeMinutes * 60 + (value - wholeMinutes)) * 1000;
You can get the current date/time via Date.now(), which gives you milliseconds since The Epoch UTC (Jan 1st 1970 at midnight).
You can create a Date instance from a given milliseconds-since-The-Epoch value via new Date(value).
So if 13.48 represents fractional minutes (13 minutes and roughly 28.79 seconds):
const minutes = 13.48;
const nowPlusThoseMinutes = new Date(Date.now() + (minutes * 60000));
Live Example:
const minutes = 13.48;
const now = Date.now();
const nowPlusThoseMinutes = new Date(now + (minutes * 60000));
console.log(nowPlusThoseMinutes);
console.log(`now = ${new Date(now)}`);
console.log(`nowPlusThoseMinutes = ${nowPlusThoseMinutes}`);
(The () around minutes * 60000 aren't necessary, the * will happen before the + either way because of operator precedence, but they can help make your intent clear to human readers.)
But you mean it to mean 13 minutes and 48 seconds:
const value = 13.48;
const wholeMinutes = Math.trunc(value);
const milliseconds = (wholeMinutes * 60 + (value - wholeMinutes)) * 1000;
const nowPlusValue = new Date(Date.now() + milliseconds);
Live Example:
const value = 13.48;
const wholeMinutes = Math.trunc(value);
const milliseconds = (wholeMinutes * 60 + (value - wholeMinutes)) * 1000;
const now = Date.now();
const nowPlusValue = new Date(now + milliseconds);
console.log(`now = ${new Date(now)}`);
console.log(`nowPlusValue = ${nowPlusValue}`);

How to increase or decrease in percentage a time in hh:mm:ss format in javascript

I have a problem with javascript. I'm pretty new, so I appreciate your help in advance.
I have a form in which I have a date in hh: mm: ss format and to which through an input field I would like to increase or decrease the hh: mm: ss by percentage. The percentage can be integer or decimal number.
That is, in one hour "example".
17:22:14 I would like to increase by 6% or if it is 14.3% decimal, or else the same value but in negative, i. e. decrease by 6% or 14.3%.
I have an example to show the percentage of an increase from a given hour but I can't do what I want to do.
With this example in PHP I would know the percentage from a date, but I don't want this, I want to know how to increase or decrease in percentage from a given time and in javascript.
<?php
$date = '08:53:34';
$parts = explode(':', $date);
$secs = $parts[0] * 3600 + $parts[1] * 60 + $parts[2];
// day has 86 400 seconds
echo $secs / 864 . '%'; // return 37.05% (you can round it)
?>
And in javascript I have this example, but the other way around. What I want is to increase or decrease not knowing the increased time from a given hour.
var time_begin = '08:00:00';
var a = time_begin.split(':');
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var start_time = Math.round((seconds/(24*60*60))*100);
Thanks in advance
You can use for solve your problem standart JS object Date();
Algorithm is easy:
1) Make Date object of current or needed date. (today variable in my code)
2) Make Date of ending date, percentage to this date we'll looking
3) Just looking for difference between today date and tomorrow
4) Now we received percent that remained until tomorrow(Or other date).
5) If your need passed percents just use 100 - ((tomorrow - today) / ONE_DAY * 100) in last varibale, before use result
6) For increasing/decreasing use example.
Example is here:
const ONE_DAY = 8.64e7; // 86400000 milliseconds
let time = "08:54:33"; // Your time where your looking %
let today = new Date();
today.setHours(time.split(":")[0], time.split(":")[1], time.split(":")[2]); // Set time from what we will looking %
let tomorrow = new Date(Date.now() + ONE_DAY).setHours("0", "0", "0");
let percent = ((tomorrow - today) / ONE_DAY * 100).toFixed("2") + "%";
// it's for increase/decrease
const HOUR = 3.6e6; // 360000
const MINUTE = 6e4; // 60000
const SECOND = 1e3; // 1000
let incPercent = 0.03; // it's mean 3%
let increased = new Date(today.getTime() + (incPercent * HOUR));

Javascript/Moment - Issue with generating time slots

I am trying to generate time slots with a gap of 15min between each one, like the following :
["15:30", "15:45", "16:00", "16:15"...]
So far, I managed to make it. However, if the current time is 15:25 (just an example) the generated array will start from 15:30 what I need instead (in this case) to generate time slots starting from 16:00 meaning that only the first time slot should be approximately away 30 min from the current time.
Currently, I have the following code :
//Used momentJS library
function getTimeStops(end) {
var roundedUp, startTime, endTime, timeStops;
roundedUp = Math.ceil(moment().utc().minute() / 30) * 30;
startTime = moment().utc().set({
minute: roundedUp
});
endTime = moment(end, 'HH:mm');
if (endTime.isBefore(startTime)) {
endTime.add(1, 'day');
}
timeStops = [];
while (startTime <= endTime) {
timeStops.push(new moment(startTime).format('HH:mm'));
startTime.add(15, 'minutes');
}
return timeStops;
}
var timeStops = getTimeStops('02:00');
console.log('timeStops ', timeStops);
You're rounding to the nearest half hour here:
roundedUp = Math.ceil(moment().utc().minute() / 30) * 30;
Round to the nearest hour instead:
roundedUp = Math.ceil(moment().utc().minute() / 60) * 60;
Edit: just realised that the above is wrong and doesn't actually answer your question.
You do need to change your roundedUp value though.
What you need to do is:
Add 30 minutes to the current time
Round it to the closest 15 minute interval
That way - at most - you'll be 7.5 minutes out.
So for step 1, add 30 minutes
var add30mins = moment.utc().add(30, 'minutes')
Now we need to find the closest 15 minute interval.
var roundTo15Mins = Math.round(add30Mins.minute() / 15) * 15;
Then you can plug that into your startTime.
HTH

Categories