I want to create timestamp list grouped by X minutes.
For instance I have min data value and max date timestamp value.
minDate = 1524548466000; // Tuesday, April 24, 2018 5:41:06 AM
maxDate = 1524577986000; // Tuesday, April 24, 2018 1:53:06 PM
So I want to create timestamp array start with Tuesday, April 24, 2018 5:40:0 AM to Tuesday,April 24, 2018, 1:55:00 PM using javascript.
I want this output:
[1524548400000,1524548700000,1524549000000,...1524578100000]
How can I do this?
Here is my solution. I just count second and compare with maxDate.
var minDate = new Date(1524548466000); // Tuesday, April 24, 2018 5:41:06 AM
var maxDate = new Date(1524577986000); // Tuesday, April 24, 2018 1:53:06 PM
var listTimestamp = [];
while (minDate.getTime() !== maxDate.getTime()) {
minDate.setSeconds(minDate.getSeconds() + 1);
listTimestamp.push(minDate.getTime());
}
console.log(listTimestamp);
Here the function you needed
function timestampGrouping(minDate, maxDate, x){
var gap = x * 60000 //60000 = 1minute;
minDate = Math.floor(minDate/gap)*gap;
maxDate = Math.ceil(maxDate/gap)*gap;
var arr = [];
while(minDate <= maxDate){
arr.push(minDate);
minDate += gap;
}
return arr;
}
var groupingArr = timestampGrouping(1524548466000, 1524577986000, 5);
console.log(groupingArr);
Math.floor and Math.ceil is to find the nearest gap value you required, and just loop thought the value to get all the minute gap you want.
minDate, maxDate and gap value can be anything you wish to.
Hope this is what you required.
You could divide the given Unix Time (Epoch Time) and divide it by a product of wanted minutes, seconds and 1000 for miliseconds.
5 minutes * 60 seconds * 1000 milliseconds = 300000
For moving events in the same slot use
Math.floor(time / 300000)
if duration is 5 min then you can set duration variable as follows.
var duration = 5 * 60 * 1000;
endTime = endTime - endTime % duration;
startTime = startTime - startTime % duration;
for(var i=startTime;i<endTime;i+=duration){
arr.push(i);
}
Related
I'm trying to write a script to subtract 5 days from a defined date but seems not working, here's my code:
var End_Day = sheet.getRange(i + 2, 20).getValue();
Logger.log(End_Day);
var End_day_2 = new Date();
End_day_2.setDate(End_Day.getDate()-5);
Logger.log(End_day_2);
and the result is not just - 5 days:
11:18:47 AM Info Sat Jun 04 00:00:00 GMT+08:00 2022
11:18:47 AM Info Fri Apr 29 11:18:47 GMT+08:00 2022
I am quite confused why the date move from Jun to Apr.
Thanks for having a look
Try:
var End_Day = sheet.getRange(i + 2, 20).getValue();
var End_day_2 = new Date(End_Day.getTime() - (5 * (1000 * 60 * 60 * 24)))
Logger.log(End_Day);
Logger.log(End_day_2);
Function:
const endDay = sheet.getRange(i + 2, 20).getValue()
const endDay2 = DateFromDaysAgo(endDay, 5)
...
function DateFromDaysAgo(startDate, number) {
if (typeof startDate === `string`) { startDate = new Date(startDate) }
return new Date(startDate.getTime() - (number * (1000 * 60 * 60 * 24)))
}
You should learn more about Date.prototype.setDate().It only changes the day of the month of a given Date instance.
As the code you posted, the day of the month of End_Day is 4, End_day_2.setDate(4 - 5) equals to End_day_2.setDate(-1) and the month of End_day_2 is April according to the console result, because there're 30 days in April, setDate(-1) means setDate(29), so you got Apr 29 at the end. That's how it goes.
One right way to do is substracting 5 days worth of milliseconds.
function addDays(date, days){
const DAY_IN_MILLISECONDS = 24 * 60 * 60000;
return new Date(date.getTime() + days * DAY_IN_MILLISECONDS);
}
console.log(addDays(new Date(), -5).toString()); // 5 days ago
I am quite confused why the date move from Jun to Apr.
It's because you're setting date on today(End_day_2) and not on your predefined date(End_day).
Change
End_day_2.setDate(End_Day.getDate()-5);
to
End_Day.setDate(End_Day.getDate()-5);
console.info(End_Day);
If what's coming from the sheet is a string, you will have to convert the date string into a date object.
The other thing is you have to work in milliseconds as #vanowm says:
606024*5 = 432000 * 1000 = 432000000
so skipping the sheet entirely:
x = new Date
> Fri May 27 2022 11:24:01 GMT-0400 (Eastern Daylight Time)
y = new Date(x - 432000000)
> Sun May 22 2022 11:24:01 GMT-0400 (Eastern Daylight Time)
This will do the trick. Works with any date and can subtract any number of days
const subtractDays = (fromDate, numDays) => {
if (!(fromDate instanceof Date)) throw 'The first argument must be a date';
return new Date(new Date().setDate(fromDate.getDate() - +numDays));
};
Weekago
function weekago() {
let dt = new Date();
dt.setDate(dt.getDate()-7);
Logger.log(dt);
return dt;
}
Five days ago
function fiveago() {
let dt = new Date();
dt.setDate(dt.getDate()-5)
Logger.log(dt);
return dt;
}
Five days from a date in a spreadsheet cell
function fivefromadateinspreadsheet() {
const v = SpreadsheetApp.getActiveSheet().getRange("A1").getValue();
let dt = new Date(v);
dt.setDate(dt.getDate()-5);//Note that does not return a date it return the numbrer of milliseconds
Logger.log(dt);
return dt;
}
You can subtract 5 days from a defined date in Google App Script by using the Utilities.formatDate() method. Here's an example:
function subtractDays() {
var date = new Date();
var subtractDays = 5;
// Subtract 5 days from the current date
date.setDate(date.getDate() - subtractDays);
// Format the new date
var newDate = Utilities.formatDate(date, "UTC", "yyyy-MM-dd");
Logger.log(newDate);
}
In this example, we first create a Date object to represent the current date. Then, we subtract 5 days from the current date by using the setDate() method. Finally, we format the new date using the Utilities.formatDate() method and log it to the console using the Logger.log() method.
You can modify the subtractDays variable to subtract a different number of days from the date, or you can use a different date object to start with.
Using javascript, how can I take a non-UTC date, add 1 UTC day, zero out time time(s), and then convert it to a ISO string?
new Date().toISOString()
2017-10-10T16:00:49.915Z
Desired UTC Datestring
2017-10-11T00:00:00.000Z
Below I get the date in milliseconds, add 1 whole day in milliseconds.
I then divide by a day in milliseconds, truncate, and then multiple again by a day in milliseconds.
var d = new Date('2017-10-10T16:00:49.915Z');
function nextDayUTC(d) {
var aDay = 1440 * 60 * 1000;
var d2 = new Date( Math.trunc((d.getTime() + aDay)/aDay)*aDay);
return d2;
}
function nextDayLocal(d) {
//basically set to start of the day
//add 36 hrs, this pretty much ensures next day
//add then reset the hours back to 0
var hr36 = 36 * 60 * 60 * 1000;
var d2 = new Date(d);
d2.setHours(0,0,0,0);
d2.setTime(d2.getTime() + hr36);
d2.setHours(0,0,0,0);
return d2;
}
console.log(d)
console.log("Next Day UTC");
console.log(nextDayUTC(d).toISOString());
console.log("Next Day Local");
console.log(nextDayLocal(d).toString());
I am getting a 16-digit Timestamp from the server.
For example : I got "1485157072432000" from the server and when I use the time stamp converter it is showing as Wed Oct 03 49032 04:43:52 GMT+0530 (India Standard Time)
However,I am getting the exact time when I remove the last 3-digits from the 16-digit number. But I'm getting 16 digit Timestamp from server. What is the way to get exact time from 16-digit Timestamp??
Since you need the microseconds precision I guess that the only solution is to use a custom object where you store all the information you need.
I would suggest you to use something like this utility developed by the GitHub user kamikane.
In particular you need the parse function that he developed:
function parse(nano) {
var ms = nano / 1000;
var ss = ms / 1000;
var mm = ss / 60;
var hh = mm / 60;
var dd = hh / 24;
var microseconds = Math.round((ms % 1) * 1000);
var milliseconds = Math.floor(ms % 1000);
var seconds = Math.floor(ss % 60);
var minutes = Math.floor(mm % 60);
var hours = Math.floor(hh % 24);
var days = Math.floor(dd);
return { microseconds: microseconds, milliseconds: milliseconds, seconds: seconds, minutes: minutes, hours: hours, days: days, toString: toString };
};
Example usage:
parse(1485157072432010);
{ microseconds: 10, milliseconds: 432, seconds: 52, minutes: 37, hours: 7, days: 17189 }
I really need your help,
Let's say my demarcation start date is: December 19, 2016 as defined by the variable x
How can I write a JavaScript function, such that it will check the present date against x and the present date against what the recurrence date will be (14) days from x as defined by the variable y.
var y = recurrence is every 14 days, thereafter from the date (x) with no end date specified (unlimited)
Ex.
function() {
if (present date == x) { alert(true) }
if (present date == y) { alert(true) }
}
You could get the number of days difference between your start date and the current date then check if that number is a multiple of 14.
function treatAsUTC(date) {
var result = new Date(date);
result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
return result;
}
function daysBetween(startDate, endDate) {
var millisecondsPerDay = 24 * 60 * 60 * 1000;
return Math.floor((treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay);
}
var demarcationdate = new Date("2016-12-19"),
today = new Date(),
days = daysBetween(demarcationdate,today),
daystill = 14 - days%14,
rec = days%14==0,
d = new Date();
d.setDate(today.getDate() + daystill);
var nextDate = (d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear());
console.log("Days diff = "+days+". Recurs today = "+rec+". Next in "+daystill+" days ("+nextDate.toString()+").");
jsFiddle
If Date.now() == 1482181410856, 14 days from now will be 1482181410856 + (14 * 24 * 60 * 60 * 1000) == 1483391010856.
let y = new Date(Date.now() + (14 * 24 * 60 * 60 * 1000));
console.log(y.toUTCString()); // "Mon, 02 Jan 2017 21:03:30 GMT"
Assuming you really want to compare precise dates, i.e. to the milliseconds, then:
var present_date = new Date();
if(present_date.getTime() === x.getTime()) alert("Today is the same date as x");
else {
var y = new Date(x.getTime());
y.setDate(y.getDate() + 14); // add 14 days
if(present_date.getTime() === y.getTime()) alert("Today is the same date as y");
}
But most of the time we want to compare dates as full days, not milliseconds, so you'd have to compare ranges instead (from midnight to 11:59PM)... In that case, I recommend using a library to make your life easier - like moment.js for instance...
Hope this helps!
This is probably a duplicate of Add +1 to current date.
If you have a start date, say 20 December, 2016, you can calculate 14 days after that by simply adding 14 days to the date. You can then check if today's date is either of those dates, e.g.
// Create a Date for 20 December, 2016 with time 00:00:00
var startDate = new Date(2016,11,20);
// Create a Date for the start + 14 days with time 00:00:00
var startPlus14 = new Date(startDate);
startPlus14.setDate(startPlus14.getDate() + 14);
// Get today and set the time to 00:00:00.000
var today = new Date();
today.setHours(0,0,0,0);
if (+today == +startDate) {
console.log('Today is the start date');
} else if (+today == +startPlus14) {
console.log('Today is 14 days after the start date');
} else {
console.log('Today is neither the start nor 14 days after the start');
}
I want to set GMT+5:30 as my timezone in jquery countdown.
Start Time for countdown is 'Thu May 20 16:00:00 IST 2010'
End Time is 'Thu May 20 17:00:00 IST 2010' as value.
+330 is my timezone given in minutes.
But my countdown starts from 00:35:00.
I would have expected the countdown to start from 01:00:00
Not sure why this is discrepancy is there.
<script type="text/javascript">
$(function () {
var endTime = '#{myBean.getCountDownDate()}';
$('#defaultCountdown').countdown({
until: endTime, format: 'HMS',
timezone: +330,
compact: true, description: '#{myBean.getCountDownDate()}'});
});
</script>
When using the until parameter the countdown plugin counts down until that time.
This will run for one hour using the correct offset.
$('#countdown').countdown({
until: $.countdown.UTCDate(+330, 2010, 6-1, 20, 17),
format: 'HMS',
compact: true
});
Since 2010:06:20:17 has already passed it will display 00:00:00.
I would bet the reason you got 00:35:00 in your countdown is that you were looking at it around 2010:06:20:16:25.
What happens when you change your End Time format to 'Thu, 20 May 2010 17:00:00 IST'?
-edit-
It looks like you're not supposed to pass the date value to until as a String. You can pass in a Date to specify the exact date/time, but a string is only supposed to be used as a time offset, which is why you always get the same amount of time remaining when you refresh.
I couldn't get Date to convert the string with the 'IST' time zone, so I ended up using 'GMT+05:30'. I also put the timezone offset in terms of hours instead of minutes.
<script type="text/javascript">
$(function () {
var endTime = "Tue, 29 Jun 2010 12:00:00 GMT+0530";
$('#defaultCountdown').countdown({
until: new Date(endTime), format: 'HMS',
timezone: +5.5,
compact: true, description: endTime.toString()});
});
</script>
to set timer with eastern timezone
<script>
setInterval(function(){
var timeZone = "America/New_York";
var TimerEndDate = "Nov 25 2022";
var endHour = 23;
var endMinute = 59;
var endSeconds = 59;
//for starting time for timer
//bydefault set to america current time
var nowDate = new Date();
var nowTimeZone = convertTZ(nowDate, timeZone);
var now = new Date(nowTimeZone.getFullYear(),nowTimeZone.getMonth(),nowTimeZone.getDate());
now.setHours(nowTimeZone.getHours(), nowTimeZone.getMinutes(), nowTimeZone.getSeconds());
var endDate = new Date(TimerEndDate+" "+endHour+":"+endMinute+":"+endSeconds);
var endDateTime = convertTZ(endDate, timeZone);
var future = new Date(endDateTime.getFullYear(),endDateTime.getMonth(),endDateTime.getDate());
future.setHours(endHour, endMinute, endSeconds);
var difference = Math.floor((future - now) / 1000);
var seconds = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
var minutes = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
var hours = fixIntegers(difference % 24);
difference = Math.floor(difference / 24);
var days = difference;
$("#seconds").text(seconds + "s");
$("#minutes").text(minutes + "m");
$("#hours").text(hours + "h");
$("#days").text(days + "d");
}, 1000);
function convertTZ(date, tzString) {
return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {timeZone: tzString}));
}
function fixIntegers(integer)
{
if (integer < 0)
integer = 0;
if (integer < 10)
return "0" + integer;
return "" + integer;
}
</script>
<span id="days"></span>
<span id="hours"></span>
<span id="minutes"></span>
<span id="seconds"></span>