Compare two Dates in SAPUI5 - date

I want to compare, whether Date A is greater than Date B. But I always get false, even if Date A is greater.
var oDatepicker = this.getView().byId("Date");
var oFormat = sap.ui.core.format.DateFormat.getInstance({ pattern: "d.M.y" });
var oDate = oFormat.format(new Date());
var oDatepickerParsed = oFormat.parse(oDatepicker.getValue());
if(oFormat.format(oDatepickerParsed) > oDate){
return true;
} else {
return false;
}
I tried to instantiate a Date-Object based on oDatepicker.getValue() to compare Date-Object with Date-Object, but there is something wrong.
var oDateObject = new Date(oDatepicker.getValue())
oDatepicker.getValue() is = '01.11.2020' type string. Whats wrong?

Did you try the DatePicker method getDateValue() which gives you "the date as JavaScript Date object. This is independent from any formatter."

Related

Compare data with present date google script

Hi i want to compare column with date (i.e "Referral Date" column)
with present day , here is what i have
function newF(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Worksheet');
var range = ss.getDataRange();
var headers = range.getValues()[0];
var colIndex = headers.indexOf("Referral Date");
var today = new Date();
var searchRange = ss.getRange(2,colIndex+1,ss.getLastRow()-1);
for (i=0;i<range.getLastRow();i++){
var dates = searchRange.getValues();
if (today.valueOf()>dates.valueOf()){
updatelFilter()
} else{
SpreadsheetApp.getUi().alert('Future Date Error');
break;
}
}
}
The problem i have is, it throws alert Future Date Error irrespective of date in column (Referral Date). Let me know if additional information is required.
My goal:
1)if date column (Referral Date) is greater than present date : Throw alert error & should not run updateFilter
2)if (Referral Date) is lesser than present date: Run updateFilter function
Issues
searchRange.getValues() yields a two dimensional array. So dates[0][0] points to a date, while dates[0] points to an array.
var dates = searchRange.getValues(); is being called inside the loop repeatedly, when it should ideally be called outside once since the value will not change; calling it inside the loop is costly and redundant
for (i=0;i<range.getLastRow();i++){ the condition can be replaced with i<dates.length if point 2 is followed
if (today.valueOf()>dates.valueOf()){ I believe is supposed to have dates[0] instead
Modified Code
function newF(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Worksheet');
var range = ss.getDataRange();
var headers = range.getValues()[0];
var colIndex = headers.indexOf("Referral Date");
var today = new Date();
var searchRange = ss.getRange(2,colIndex+1,ss.getLastRow()-1);
var dates = searchRange.getValues().map(d=>d[0]);
for (i=0;i<dates.length;i++) {
if (today.valueOf()>dates[i].valueOf()){
updateFilter()
} else {
SpreadsheetApp.getUi().alert('Future Date Error');
break;
}
}
}
To run updateFilter only if no future dates
Replace the loop with the following -
if(dates.some(d => today.valueOf() < d.valueOf())) {
SpreadsheetApp.getUi().alert('Future Date Error');
} else {
for (let i=0; i<dates.length; i++) {
updateFilter();
}
}

How to convert DateTime to Duration in flutter?

I have trouble to convert input like 72:46:00.15768 to duration like 4366 minutes
I tried this but return null after trying the .inMinutes()
var _lastConso = lastConsoString3!=null ? DateTime.parse(lastConsoString3) : DateTime.now();
Diff = DateTime.now().difference(_lastConso);
DurationDiff=Diff.inMinutes;
Try this
/// 72:46:00.15768
var lastConsoString3= Duration(hours:72,minutes: 46,seconds: 00,milliseconds: 15768);
var _lastConso =DateTime.now().subtract(lastConsoString3);
var diff = DateTime.now().difference(_lastConso);
print( diff.inMinutes); /// 4366 your answer
Maybe your variable that named lastConsoString3 not well formatted for DateTime. Below code works fine. And you need to write var or exact type of variable.
var _lastConso = DateTime.now().add(Duration(days: -12)); //your parsed date
var diff = DateTime.now().difference(_lastConso);
var durationDiff = diff.inMinutes;

Google script not recognising date

I'm trying to write some code to check values in a spreadsheet column to see if they are valid dates. However, even if I put in a date in a cell with the format set to date, it doesn't seem to recognise it as a date. When I debug the date objects are listed as "new Date" but if I attempt to ask Logger to getDate() I receive the following error :
TypeError: Cannot find function getDate in object Sat Jun 05 2010 01:00:00 GMT+0100 (BST). (line 15, file "myCode")
I can set my objects as dates by calling 'new Date()' which means that they are recognised as dates but this changes all the objects to dates whether they should be or not.
Here is my code:
function onMyPress(){
var sheet = SpreadsheetApp.getActive().getActiveSheet()
var myRange = sheet.getRange(2,2,8,1)
var myValues = myRange.getValues()
for (i=0; i<8; i++){
var testDate = myValues[i]
if (isDate(testDate)) {sheet.getRange(i+2,3,1,1).setValue("Date")
}
else{
sheet.getRange(i+2,3,1,1).setValue("Not Date")
}
Logger.log(testDate.getDate())
}
}
function isDate(testDate) {
if (Object.prototype.toString.call(testDate) !== "[object Date]") {
return false;
}
else {
return true;
}
}
Thanks for looking.
The problem is that getValues() returns a 2D array and you script assigns a "row" (a
JavaScript array) instead of cell value (a JavaScript string, Date, etc.) to testDate on the following line
var testDate = myValues[i]
One alternative is to replace the above code line by by something like the following:
var testDate = myValues[i][0]
assuming that your dates are on the first column.
"Cannot find function getDate in object" means that you are calling getDate() on an object that is NOT a Date object.
I am guessing "testDate" is a String object? If you step through the code, does it go into the "else" clause?
You need to:
Check that your String object contains a correctly formatted date
(which seems to be the case)
Then CONVERT it to a Date object, like this: var realDate = new Date(testDate);
See working example here:
https://jsfiddle.net/uyowax8o/
// Convert to Date object
var realDate = new Date(testDate);
// This now works
alert(realDate.getDate());

Difference of two locale date in jquery

I am getting the date from CJuidatepicker with language such de,en,nl.
Now i need to find the difference between two dates in jquery accordnig to the language selected.
My Code is
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate()-1;
var output = d.getFullYear() + '-' +
((''+month).length<2 ? '0' : '') + month + '-' +
((''+day).length<2 ? '0' : '') + day;
var dateString1 = $('#Jobs_valid_date').val();
var dateString2= output;
var dateDiff = function ( dateString2, dateString1 ) {
var diff = Math.abs(dateString2 - dateString1);
if (Math.floor(diff/86400000)) {
return Math.floor(diff/86400000);
} else if (Math.floor(diff/3600000)) {
return Math.floor(diff/3600000);
} else if (Math.floor(diff/60000)) {
return Math.floor(diff/60000);
} else {
return "< 1 minute";
}
};
var new_date = dateDiff(new Date(dateString2), new Date(dateString1));
var sum = (parseInt(new_date * feature) + parseInt(fixed))
It retuns NAN.. Please help me to solve this
Doing it from scratch is not recommended for several reasons. If using a library is not a constraint, use moment.js. It has methods to calculate date differences. It has internationalization support too. In case your locale is not supported you can add it yourself. If you add a new locale, you are welcome to contribute it to the moment.js community.
Try this out, this worked for me. I wanted to calculate difference between the 2 dates which the client inputs.
function calculate(start_date,end_date)
{
var t1= start_date ;
var t2= end_date;
// The number of milliseconds in one day
var one_day=1000*60*60*24;
//Here we need to split the inputed dates to convert them into standard format
var x=t1.split(“/”);
var y=t2.split(“/”);
//date format(Fullyear,month,date)
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0]);
//Calculate difference between the two dates, and convert to days
numberofDays=Math.ceil((date2.getTime()-date1.getTime())/(one_day));
// numberofDays gives the diffrence between the two dates.
$(‘#Input_type_text).val(numberofDays);
}

Check date range vs. some other date ranges for missing days

Here is what I want to do:
I got a date range from e.g. 03.04.2013 to 23.04.2013 - that's my main range.
Now I have the possibility to create some own time ranges (e.g. 04.04.2013 to 09.04.2013 and 11.04.2013 to 23.04.2013). Those have to cover the whole main range, so every day of the main range (excluding weekens) needs an corresponding day in my own time ranges.
My plan would be to create an Array for the main range. Then I check each day of my own time ranges against the main range. If there is an accordance, I would remove the day from the main range.
So in the end, if everything is ok, there would be an emtpy array, because all days are covered by my own time ranges. If not, then the days not covered would still be in the main range and I could work with them (in this example: 03.04.2013, 10.04.2013)
Does anybody have an better idea to solve this problem? NotesDateTimeRanges?
I would add the dates into a sorted collection and then a "pirate algorithm". Look left, look right and if any of the looks fails you can stop (unless you want to find all missing dates).
Off my head (you might need to massage the final list to store the value back):
var AbsenctSince:NotesDateTime; //Start Date - stored in the NotesItem
var endDate:NotesDateTime; // Return, could be in Notes or Today
var wfDoc:NotesDocument = docApplication.getDocument();
var responseCDs:NotesDocumentCollection = wfDoc.getResponses();
var docResponse:NotesDocument;
var nextResponse:NotesDocument;
//Get the date, which limits the function - if there is a return information, then this is the limit, else today
AbsenctSince = wfDoc.getDateTimeValue("AbsentSince") ;
if (wfDoc.hasItem("ReturnInformationDat")) {
endDate = wfDoc.getDateTimeValue("ReturnInformationDat");
} else {
endDate = session.createDateTime("Today");
}
//Get all days between two dates - as pure Java!
var dateList:java.util.List = getWorkDayList(AbsenctSince.toJavaDate(), endDate.toJavaDate());
// Looping once through the reponse documents
var docResponse = responseCDs.getFirstDocument();
while (docResponse != null) {
nextResponse = responseCDs.getNextDocument(docResponse);
var CDValidSince:NotesDateTime = docResponse.getDateTimeValue("CDValidSince");
var CDValidTill:NotesDateTime = docResponse.getDateTimeValue("CDValidTill");
// Now we need get all days in this range
var removeDates:java.util.List = getWorkDayList(CDValidSince.toJavaDate(),CDValidTill.toJavaDate());
dateList.removeAll(removeDates);
docResponse.recycle();
docResponse = nextResponse;
}
// Both docs are null - nothing to recycle left
// Now we only have uncovered dates left in dateList
docApplication.replaceItemValue("openDates", dateList);
// Cleanup
try {
AbsenctSince.recycle();
endDate.recyle();
wfDoc.recycle();
responseCDs.recycle();
} catch (e) {
dBar.error(e);
}
function getWorkDayList(startDate, endDate) {
var dates:java.util.List = new java.util.ArrayList();
var calendar:java.util.Calendar = new java.util.GregorianCalendar();
calendar.setTime(startDate);
while (calendar.getTime().before(endDate)) {
var workDay = calendar.get(calendar.DAY_OF_WEEK);
if (workDay != calendar.SATURDAY && workDay != calendar.SUNDAY) {
var result = calendar.getTime();
dates.add(result);
}
calendar.add(java.util.Calendar.DATE, 1);
}
return dates;
}
I've done it this way now (seems to work so far):
var dateArray = new Array();
var responseCDs:NotesDocumentCollection = docApplication.getDocument().getResponses();
var dt:NotesDateTime = session.createDateTime("Today");
var wfDoc = docApplication.getDocument();
dt.setNow();
//Get the date, which limits the function - if there is a return information, then this is the limit, else today
var AbsenctSince:NotesDateTime = session.createDateTime(wfDoc.getItemValue("AbsentSince").toString().substr(0,19));
if (wfDoc.hasItem("ReturnInformationDat")) {
var endDate:NotesDateTime = session.createDateTime(wfDoc.getItemValue("ReturnInformationDat").toString().substr(0,19));
} else {
var endDate:NotesDateTime = session.createDateTime("Today");
}
//Get all days between two dates
dateArray = getDates(AbsenctSince, endDate);
for (var i=dateArray.length-1; i >= 0 ; i--) {
var checkDate:NotesDateTime = session.createDateTime(dateArray[i].toString().substr(0,19));
var day = checkDate.toJavaDate().getDay();
//Remove weekends first
if ((day == 6) || (day == 0)) { //6 = Saturday, 0 = Sunday
dBar.info("splice: " + dateArray[i]);
dateArray = dateArray.splice(i,1);
} else {
var docResponse = responseCDs.getFirstDocument();
//Work through all response docs to check if any date is covered
while (docResponse != null) {
var CDValidSince:NotesDateTime = session.createDateTime(docResponse.getItemValue("CDValidSince").toString().substr(0,19));
var CDValidTill:NotesDateTime = session.createDateTime(docResponse.getItemValue("CDValidTill").toString().substr(0,19));
//checkDate covered? If yes, it will be removed
if (checkDate.timeDifference(CDValidSince)/86400 >= 0 && checkDate.timeDifference(CDValidTill)/86400 <= 0 ) {
dBar.info("splice: " + dateArray[i]);
dateArray = dateArray.splice(i,1);
}
docResponse = responseCDs.getNextDocument();
}
}
}
docApplication.replaceItemValue("openDates", dateArray);
And I'm using this function (adopted from this question here):
function getDates(startDate:NotesDateTime, endDate:NotesDateTime) {
var dateArray = new Array();
var currentDate:NotesDateTime = startDate;
while (endDate.timeDifference(currentDate) > 0) {
dateArray.push( currentDate.getDateOnly() );
currentDate.adjustDay(1);
}
return dateArray;
}