I have a sending two timestamp start timestamp and end timestamp I have to check if the current timestamp in between the start and end timestamp then I have to change the variable value to true otherwise false.
{
"start_time":"2020-04-23T06:49:55.510Z",
"end_time":"2020-04-23T20:49:55.510Z",
"form_type":"5e54b4e4d76bf807091043ae",
"book_id":"5e56469d42f0c5647625fd45",
}
i am sending the data in this from in mongodb
sudo code something like this
var check = false
currentTime = Date.now()
if(currentTime < Start_time && currentTime < end_time)
{
check = true
}
I am not able to make a query for this.
currentTime = new Date();
db.model.find({"start_time" : { $gte : new
ISODate(currentTime.toISOString()) },
"end_time" : { $lte : new
ISODate(currentTime.toISOString()) }
});
Can you please try this Mongo query and check whether it is working or not? Please change the code according to your need.
You can use moment.js for that.
moment().utc();
This returns the current timestamp.
Then You need to convert your timestamp into a moment object.
compare_time = moment.utc('2020-04-21T06:49:55.510Z', 'YYYY-MM-DD[T]HH:mm:ss[Z]');
After doing that compare that to the current time using "isAfter()". Here is a working example
var current = moment.utc();
var compare_time = moment.utc('2020-04-21T06:49:55.510Z', 'YYYY-MM-DD[T]HH:mm:ss[Z]');
current.isAfter(compare_time); // true
You need to compare Date objects like so
var obj={
"start_time":"2020-04-23T06:49:55.510Z",
"end_time":"2020-04-23T20:49:55.510Z",
"form_type":"5e54b4e4d76bf807091043ae",
"book_id":"5e56469d42f0c5647625fd45",
}
var check=Date.parse(obj.start_time)<Date.now() && Date.now()<Date.parse(obj.end_time)
A fairly simple comparison to do using .getTime() on the Date object.
const jsonObject = {
"start_time": "2020-04-23T06:49:55.510Z",
"end_time": "2020-04-23T20:49:55.510Z",
"form_type": "5e54b4e4d76bf807091043ae",
"book_id": "5e56469d42f0c5647625fd45",
}
const startTime = new Date(jsonObject.start_time).getTime();
const endTime = new Date(jsonObject.end_time).getTime();
const currentTime = new Date().getTime();
console.log(startTime, currentTime, endTime);
console.log(startTime <= currentTime && currentTime <= endTime);
You can use mongodb-aggregation.
Your query would be like:
currentTime = new Date()
db.model.aggregate([
{
$set: {
value: {
$cond: [{currentTime: {$gt: "$start_time", $lt: "$end_time"}}, true, false]
}
}
}
])
Related
I tried using the intervalToDuration function from date-fns but I keep getting an error that says End Date is invalid.
My code is as follows
import { intervalToDuration} from "date-fns";
remaining() {
const now = new Date();
const end = this.endDate;
return intervalToDuration({
start: now,
end: end,
});
},
this.endDate is dynamically populated but for this question is equal to 2021-02-26T00:00:00.000Z
Since your endDate variable is coming from an API, it is being stored as a string, not a date.
Calling intervalToDuration is expecting an interval object to be passed as the parameter. An interval consists of two Dates or Numbers (unix timestamp)
To correct this, you must convert endDate to a date object, below is an untested example;
const remaining = () => {
const endDate = "2021-02-26T00:00:00.000Z";
const now = new Date();
const end = new Date(endDate);
return intervalToDuration({
start: now,
end: end
});
};
const dur = remaining();
console.log("DURRATON ", JSON.stringify(dur));
//
// Response == DURRATON {"years":0,"months":1,"days":8,"hours":15,"minutes":42,"seconds":0}
//
Notice : This does not handle timezones correctly. new Date() will create a datetime in the client timezone where it appears that your response from the API is in GMT timezone
I am getting date in string format from API.
End Date 2014-06-03T06:16:52. I need to write an if-else logic and compare the end date and current date.If end date is less than current date then show customer as In Active and if end date is greater than display the Customer as Active.
I have tried following logic but I am not able to understand and get today's time in string fromat.
this.endDate = this.sampleData != null ?
this.sampleData.customerStartDate : null;
this.currentDate = new Date();
var dd = this.currentDate.getDate();
var mm = this.currentDate.getMonth() + 1;
var yyyy = this.currentDate.getFullYear();
this.currentDate = new Date().toLocaleString()
console.log('End Date', this.endDate);
console.log('Current Date: ', this.currentDate);
if (this.endDate == null) {
this.customerStatus = 'Active';
} else {
this.customerStatus = 'In Active';
}
I am getting current date as Current Date: 4/2/2019, 1:23:34 AM
I want to be able to get in same format as End Date.
My main task is to compare the dates how do I achieve it ?
Ideally you want to clean up the date you're getting from an API, and convert it to a JS Date object. You can do this by keeping only the 2014-06-03T06:16:52 part, and giving it to the new Date() constructor.
You can get the current date by calling new Date() without parameters.
You can the turn the dates in to numbers by calling getTime() on each.
You can then compare the numbers.
const incoming_date = new Date('2014-06-03T06:16:52');
const current_date = new Date();
if (incoming_date.getTime() < current_date.getTime() {
// incoming_date is before current_date
} else {
// current_date is before incoming_date
}
as simple as this:
let date=new Date("2014-06-03T06:16:52")
date>new Date()
you could try to express dates in ms since the Unix Epoch with getTime() and compare them
if (currDate.getTime() > endDate.getTime()) {
// set customer to inactive
} else {
// keep customer active
}
I personally like to use moment() for javascript dates. You really just need to have it compare the same format, so you could have something like:
this.currentDate = moment().toISOString();
const dataDate = this.sampleData ? this.sampleData.customerStartDate : null;
this.endDate = moment(dataDate).toISOString();
if (this.endDate > this.currentDate) {
this.customerStatus = 'Active';
} else {
this.customerStatus = 'Inactive';
}
How to check if time is the same for Moment objects with different dates?
For example I have object like
const endDate = moment().add(30, 'days').endOf('day');
and I want to check if some moment object is endOf day.
private isEndOfDay(dateTime: string) {
const m = moment().endOf('day');
return m.isSame(dateTime, 'minute');
}
const receivedDateFormat: string = 'YYYY-MM-DD hh:mm:ss';
this.isEndOfDay(this.endDate.format(this.receivedDateFormat))
But for this case, when I pass "minute" parameter, it will check minute, hour, day, month and year... which isn't what I want to check.
The part of the documentation that explains that behaviour is
When including a second parameter, it will match all units equal or larger. Passing in month will check month and year. Passing in day will check day, month, and year.
So, if you just want to compare the minutes, you'll need to do something like
endDate.minute() === startDate.minute()
To compare the time only, format() the dates
endDate.format('HH:mm:ss') === startDate.format('HH:mm:ss')
To compare only time part you can set a given date (year, month and day) to your input.
Please note that passing 'minute' to isSame will ignore seconds.
Here a live sample:
function isEndOfDay(dateTime) {
let m = moment().endOf('day');
let m2 = moment(dateTime);
m2.set({
y: m.year(),
M: m.month(),
D: m.date()
});
return m.isSame(m2, 'minute');
}
var endDate = moment().add(30, 'days').endOf('day');
const receivedDateFormat = 'YYYY-MM-DD hh:mm:ss';
var ret = isEndOfDay(endDate.format(this.receivedDateFormat))
console.log(ret);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Another way to to is checking only units that matter for you:
function isEndOfDay(dateTime) {
let m = moment().endOf('day');
let m2 = moment(dateTime);
if( m.hours() === m2.hours() &&
m.minutes() === m2.minutes() &&
m.seconds() === m2.seconds() ){
return true;
}
return false;
}
var endDate = moment().add(30, 'days').endOf('day');
const receivedDateFormat = 'YYYY-MM-DD hh:mm:ss';
var ret = isEndOfDay(endDate.format(this.receivedDateFormat))
console.log(ret);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
See Get + Set section of the docs to see how to get and set units of moment objects.
Desired Output: I have a date variable being passed that needs to be compared to today's date and return weather it is before or after today. I would then like to return "Yes" or "No" to indicate weather it is active or not.
<script>
function calculate(currentlyEffective) {
var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
var expDate = currentlyEffective.Expiration_Date;
expDate = new Date(expDate).toUTCString();
var result = "";
if (expDate < now_utc) {
result = "No"
}
else {
result = "Yes"
}
return result;
}
</script>
Problem:
Some of the dates being passed do not have a value because they are not expired yet. This returns Thu, 01 Jan 1970 00:00:00 GMTThe desired output would be "Yes" here even though the date would be less than today because it has no expiration date making it "Yes" still active.
Something isn't happening correctly in the calculation. My return value is always "Yes"
Questions:
Am I comparing these dates correctly with my if else function?
Even in an instance where I have a date in expDate that is before today I still get "Yes" as my return value. What am I doing wrong?
Youre comparing a string and a Date Object with < ? What do you expect? You dont need the time string, you need the time as a number:
var now=new Date().getTime();//current time as number (ms since...)
var old=new Date(timestring).getTime();//time as number with a timestring ("12:20 ...")
if(now<old){
alert("future date!");
}
Full code:
function calculate(currentlyEffective) {
var now = new Date().getTime();
var expDate = currentlyEffective.Expiration_Date;
expDate = new Date(expDate).getTime();
return expDate<now?"Yes":"No";
}
As RobG pointed out, this can be shortified, as using < on two objects, trys to convert them to number, wich does in fact call getTime:
var calculate=(currentlyEffective)=>new Date(currentlyEffective.Expiration_Date)<new Date()?"Yes":"No";
I have 3 variables: (1)Date (2) StartTime (3) EndTime
I would like to bring them as two variables (1)Date and StartTime (2) Date and EndTime, so that I can create a google calendar event.
As per my understanding, in order to create a google calendar event I need to pass ISO String format for event timings. Can anyone check the below code and help me with the missing piece.
function createEvent(title,Dt,startTime,endTime,col) {
var calendarId = '_____#group.calendar.google.com';
Logger.log(Dt); //2016-07-21
Logger.log(startTime); // 11:55 AM
Logger.log(typeof(startTime)); //string
//Help Needed to convert + to ISO
var event = {
summary: title,
start: {
dateTime: startISO
},
end: {
dateTime: endISO
},
colorId: col
};
event = Calendar.Events.insert(event, calendarId);
Logger.log('Event ID: ' + event.getId());
You can use .toISOString() on the Date object to get an ISO String, but Google Calendar is requesting a slightly different format than this, but it is a quick fix. Start with a normal conversion:
(new Date()).toISOString(); // "2016-07-29T00:00:00.000Z"
var startTime = new Date();
var isoStartTime = startTime.toISOString();
If you need to make the Date from separate objects you can:
var yourDate = '2016-07-29';
var yourTime = '11:55 AM';
var startTime = new Date(yourDate);
startTime.setHours(yourTime.split(':')[0]); // 11
startTime.setMinutes(yourTime.split(':')[1].substr(0,2)); // 55
startTime = startTime.toISOString(); // "2016-07-29T11:55:00.000Z"
Then change it to what Google's looking for:
// To RFC 3339...
startTime.substr(0,startTime.length-5)+'Z'; // "2016-07-29T11:55:00Z"
Or
//if the "startTime = startTime.toISOString()" assignment happened
startTime.split('.')[0]+'Z';
//if startTime is a Date object, not a string
startTime.toISOString().split('.')[0]+'Z';
You can also (and probably preferrably) use numbers instead of strings for all that; if you pass hours and minutes separately it could look cleaner than that string operation:
var startTime = new Date(yourDate);
startTime.setHours(yourHours); // string or int
startTime.setMinutes(yourMinutes); // string or int