Javascript - Difference dates with 120s - momentjs

I need to show difference between now and now+120 seconds. I need too compare difference in seconds, not in minutes. The code looks like
this.nextDate = moment().add(120, 'seconds');
this.timer = setInterval(() => {
this.currentDate = moment();
this.diff = moment.duration(this.nextDate.diff(this.currentDate));
}, 1000)
The problem: Console.log(this.diff.seconds()) return that difference is 60 seconds (and going down), not 120.
So: What´s the problem? Why moment.js doesn´t get 120s?

There are two problem:
In moment.duration() if you pass just one parameter by default it is the number of milliseconds, so you can moltiply the number for 1000 (moment.duration(diff * 1000)) or you can pass a second parameter indicating the type of time unit like this moment.duration(diff, 'seconds') or passing an object instead of two paramters like moment.duration({ seconds: diff }).
the second problem is the function for extract the seconds from the duration object, you used .seconds() that it return a number between 0 and 59, if you want the length of the duration in seconds you must use .asSeconds()
For me the duration it's a plus in this case, you can use a simple countdown of second like that:
const nextDate = moment().add(120, 'seconds');
const timer = setInterval(() => {
const currentDate = moment();
const seconds = nextDate.diff(currentDate, 'seconds');
console.log(seconds);
}, 1000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Else you want or you need to use duration this is the code:
const nextDate = moment().add(120, 'seconds');
const timer = setInterval(() => {
const currentDate = moment();
const seconds = nextDate.diff(currentDate, 'seconds');
const duration = moment.duration(nextDate.diff(currentDate, 'seconds'), 'seconds'); // Alternatively const duration = moment.duration({ seconds });
console.log('duration: ', duration.asSeconds());
}, 1000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Related

How to use for loop to create multiple dates?

I have a function here that gets the date, and adds one week to it:
func thingy() {
let currentDate = Date()
var dateComponent = DateComponents()
dateComponent.day = 7
let futureDate = Calendar.current.date(byAdding: (dateComponent*i), to: currentDate)
print(futureDate!.formatted())
}
This gets the current date, adds one week to it, and prints out that date.
I want to get a for loop that will give the date, for example maybe 10 weeks in the future, maybe looking something like this:
for i in 1...num[ex: 11] {
let currentDate = Date()
var dateComponent = DateComponents()
dateComponent.day = 7
let futureDate = Calendar.current.date(byAdding: (dateComponent*i), to: currentDate)
let match = (title: "Test", date: futureDate)
}
I get this error:
Referencing operator function '*' on 'DurationProtocol' requires that 'DateComponents' conform to 'DurationProtocol'
How do I fix this?
I would advise adding .weekOfYear to the date. E.g., to get an array of Date representing the next ten weeks:
let calendar = Calendar.current
let today = calendar.startOfDay(for: Date())
let dates = (1 ... 10)
.compactMap { calendar.date(byAdding: .weekOfYear, value: $0, to: today) }

I'm using moment.js diff to compare two times, but the result is incorrect

I'm using moment.js diff to compare two times,but the result is incorrect
var moment = require('moment.js')
console.show()
var mydate = new Date();
myhours = mydate.getHours()
myminutes = mydate.getMinutes()
var a = moment([2007, 0, 29]);
var b = moment([2007, parseInt(myhours), parseInt(myminutes)]);
log(b.diff(a,'minutes'))
I want the result to be correct
You are trying to use the hours and minutes of myDate like month and day in the array to pass at moment constructor.
You can change b with this code:
const b = moment([2007, 0, 29, parseInt(myhours), parseInt(myminutes)]);
or using the methods of moment:
const b = moment().year(2007).startOf('minute');
.year() set the year of date, and .startOf() rounds the time to start of minute.
This can be a solution, if I understood what do you want:
const moment = require('moment.js');
const a = moment([2007, 0, 29]); // 2007-01-29 00:00:00
const b = moment().year(2007).startOf('minute'); // 2007-01-12 14:34:00
console.log(b.diff(a, 'minutes')); // -23606 -> use Math.abs(b.diff(a, 'minutes')) for the absolute value, your choice.

Google Earth Engine: Extract second largest value from annual observations?

In Google Earth Engine, is it possible to extract the annual second largest and second smallest value and construct an imagecollection?
Apparently, there is no build-in reducer for this purpose.
Here is my code for getting the min, please guide me on how to get the second max and min.
Thank you!
Here is the code:
var startDate = ee.Date('2001-01-01'); // set start time for analysis
var endDate = ee.Date('2021-12-31'); // set end time for analysis
// calculate the number of year to process
var nyears = ee.Number(endDate.difference(startDate,'year'));
//init a time band
var createTimeBand= function(image) {
return image.addBands(image.metadata('system:time_start')
.divide(1e18))
// .divide(1000*60*60*24*365))
}
var sst = ee.ImageCollection('MODIS/006/MOD11A1').select('LST_Day_1km')
.filterDate(startDate, endDate)
.map(createTimeBand)
var byyearMin = ee.ImageCollection(
// map over each month
ee.List.sequence(0,nyears).map(function (n) {
// calculate the offset from startDate
var ini = startDate.advance(n,'year');
// advance just one month
var end = ini.advance(1,'year');
// filter and reduce
return sst.filterDate(ini,end)
.select(0).min()
// .sort('LST_Day_1km').reverse().first()
.multiply(0.02)
.subtract(273.15)
.set('system:time_start', ini.millis());//convert time to number
}));
var startDate = ee.Date('2001-01-01'); // set start time for analysis
var endDate = ee.Date('2021-12-31'); // set end time for analysis
// calculate the number of year to process
var nyears = ee.Number(endDate.difference(startDate,'year'));
//init a time band
var createTimeBand= function(image) {
return image.addBands(image.metadata('system:time_start')
.divide(1e18))
// .divide(1000*60*60*24*365))
}
var sst = ee.ImageCollection('MODIS/006/MOD11A1').select('LST_Day_1km')
.filterDate(startDate, endDate)
//.map(createTimeBand)
var byyearMin = ee.ImageCollection(
// map over each month
ee.List.sequence(0,nyears).map(function (n) {
// calculate the offset from startDate
var ini = startDate.advance(n,'year');
// advance just one month
var end = ini.advance(1,'year');
var sortedDays = sst.filterDate(ini,end)
.sort('LST_Day_1km')
.toList(sst.size())
var secondLargest = ee.List(sortedDays.get(1))
var secondSmallest = ee.List(sortedDays.get(-1))
var collection = ee.Image(secondLargest)
.addBands(secondSmallest).rename(['secondLargest', 'secondSmallest'])
.multiply(0.02)
.subtract(273.15)
return collection
.set('system:time_start', ini.millis()) //convert time to number
.set('Date', ee.Date(ini))
}));
print(byyearMin)

Working with Date, Time in Google Apps Script

I need help with some quick coding with google apps script, linking to my googlesheets spreadsheet.
In the googlespreadsheets, I have a cell with the value “26-Jun-2020”. It is a date.
I want to use google apps script to calculate the number of days difference between that date (“26-Jun-2020”) and today’s day, but it won’t do the calculation for me somehow.
If I print only “expiry_date[i]” using Logger.log(expiry_date[i]), it will provide the output “Fri Dec 17 2021 01:00:00 GMT-0500 (Eastern Standard Time) “
function Put_Options_Expiry_Alert() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Long equity (sell puts)");
//var timeZone = AdsApp.currentAccount().getTimeZone(); //Get timezone of current spreadsheet
var status = sheet.getRange("F:F").getValues();
var expiry_date = sheet.getRange("M:M").getValues();
var potential_capitaloutlay_USD = sheet.getRange("Z:Z").getValues();
Logger.log("Length of status = " + status.length);
Logger.log("Length of expiry_date = " + expiry_date.length);
Logger.log("Length of potential_capitaloutlay_USD = " + potential_capitaloutlay_USD.length);
for (var i = 0; i < status.length; i++) {
if (status[i] == "Entered") { //Evaluate if this is a live Put position
//Calculate the time difference of two dates using date2. getTime() – date1. getTime();
//Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (1000*60*60*24)
Logger.log("expiry date is = "+expiry_date[i]);
Logger.log("today's date is = "+Date());
var days_to_expiry = dateDiffInDays(expiry_date[i],Date());
Logger.log(days_to_expiry);
}
}
}
// Function that returns the number of days difference between DateA and DateB
// DateA and DateB are javascript Date objects
function dateDiffInDays(DateA, DateB) {
var milliseconds_per_day = 1000 * 24 * 60; // number of milliseconds in a day
const utcA = Date.UTC(2021, DateA.getMonth(), DateA.getDate());
const utcB = Date.UTC(2020, DateB.getMonth(), DateB.getDate());
return Math.floor((utc2 - utc1) / milliseconds_per_day);
}
function timeDiffDays(Start, End) {
var day = 86400000;
var t1 = new Date(Start).valueOf();
var t2 = new Date(End).valueOf();
var d = t2 - t1;
return Math.floor(d / day);
}

How i can get default date if more than 6 hours have passed?

How i can get default date if more than 6 hours have passed?
how i get relative time
let date = 24-05-2021 13:55
const relativeTime = moment(date, 'DD-MM-YYYY HH:mm').fromNow()
I saw examples but I can't figure it out, my English is very bad
Thanks for the help, I solved the problem like this, if someone needs a solution.
const date = data.date
let dateNow = moment(new Date(), 'DD-MM-YYYY HH:mm')
let postDate = moment(date, 'DD-MM-YYYY HH:mm')
let result = dateNow.diff(postDate, 'hours')
console.log(result)
if (result <= 6) {
/*if less than 6 hours have passed i return relative date format 2 hours ago*/
const relativeTime = moment(date, 'DD-MM-YYYY HH:mm').fromNow()
data.date = relativeTime
return { data }
}else {
/* if more than 6 hours have passed i return original date format 25-05-2021 14:01*/
return { data }
}

Resources