How to compare two dates in C++Builder. 1 date from MaskEdit, 2 date from Date() - date

I have to compare two dates.
The first one I get from the TMaskEdit component with the DD-MM-YYYY mask.
I get the second date from the Date() function.
I tried something like this:
String MaskEditDate = me3->Text.Trim();
String ActualDate = Date().FormatString("DD-MM-YYYY");
TDate TDMaskEditDate = StrToDate(MaskEditDate);
TDate TDActualDate = StrToDate(ActualDate);
if (TDMaskEditDate > TDActualDate)
{
ShowMessage("TDMaskEditDate > TDActualDate");
}
if (TDMaskEditDate == TDActualDate)
{
ShowMessage("TDMaskEditDate == TDActualDate");
}
if (TDMaskEditDate < TDActualDate)
{
ShowMessage("TDMaskEditDate < TDActualDate");
}
But, when I try to convert a string to a date, I get an error message like '2000-01-01' is not a valid date and I do not know why.

StrToDate() parses the input string according to the format specified by the global ShortDateFormat and DateSeparator formatting variables in the SysUtils unit. Those variables are initialized at app startup to your OS's current user locale. This is documented behavior in BCB's help file.
So clearly, one of the input strings you pass to StrToDate() does not match the format that your OS is using for dates, which is why you get the error.
To do what you are attempting, you would have to update those formatting variables to match the format used by your input (as the overloaded version of StrToDate() that takes a TFormatSettings as input did not exist yet in BCB6). And there is absolutely no reason to take a TDate from Date(), convert it to a String, and then parse it back into a TDate, that is just redundant.
Try this instead:
String MaskEditDate = me3->Text.Trim();
TDate TDActualDate = Date();
String oldShortDateFormat = ShortDateFormat;
Char oldDateSeparator = DateSeparator;
ShortDateFormat = "DD-MM-YYYY";
DateSeparator = '-';
TDate TDMaskEditDate = StrToDate(MaskEditDate);
ShortDateFormat = oldShortDateFormat;
DateSeparator = oldDateSeparator;
However, you really should not be using a T(Mask)Edit for date input anyway. A much safer option is to use the TDateTimePicker control instead. Set its Kind property to dtkDate and then read its Date property when needed. There is no need to process your date values using strings at all:
TDate TDDateTimePickerDate = DateTimePicker1->Date;
TDate TDActualDate = Date();
if (TDDateTimePickerDate > TDActualDate)
{
ShowMessage("TDDateTimePickerDate > TDActualDate");
}
else if (TDDateTimePickerDate == TDActualDate)
{
ShowMessage("TDDateTimePickerDate == TDActualDate");
}
else //if (TDDateTimePickerDate < TDActualDate)
{
ShowMessage("TDDateTimePickerDate < TDActualDate");
}
Alternatively:
#include <DateUtils.hpp>
TDate TDDateTimePickerDate = DateTimePicker1->Date;
TDate TDActualDate = Date();
switch (CompareDate(TDDateTimePickerDate, TDActualDate))
{
case GreaterThanValue:
ShowMessage("TDDateTimePickerDate > TDActualDate");
break;
case EqualsValue:
ShowMessage("TDDateTimePickerDate == TDActualDate");
break;
case LessThanValue:
ShowMessage("TDDateTimePickerDate < TDActualDate");
break;
}

Related

Compare two Dates in SAPUI5

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."

weekday & month end identification

in the particular google scripting logic I have a requirement where I need to set a flag to true if the given date is a weekday or if it is a month-end.
Example:
the flag should be set to true if the date is 5/11/2020 or 5/15/2020 or 5/31/2020. However, the flag should remain false for the dates like, 5/16/2020 or 5/30/2020
Please let me know if there are any built in functions or any code snippets that I can enhance myself.
Regards
KK
You can work with the JavaScript Date object and compare getDay() to 0 or 6 for weekends, in which case flag is false.
For the month end, there are many ways to do it, but I find adding a method to Date.prototype is a nice way to go about this. So you would add 1 day to the date and compare the months, flag is true if they are different.
Example:
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function flagDate() {
var today = new Date();
var flag;
if(today.getDay()==6 || today.getDay()==0){
// Today is weekend
flag = false;
} else{
flag = true;
}
if(today.addDays(1).getMonth() != today.getMonth()){
// Today is the end of the month
flag = true;
}
return flag;
}
References:
Date()
To capture the day of the week use Date.getDay() and then check it against your requirements. Remember that 0 = Sunday, 1 Monday, etc…:
const someDate = isWeekday( new Date() ); // This is the date you are checking
// if it is weekday
if( date.getDay() != 0 || date.getDay() != 6 ){
// do something
} else {
// if it is weekend, do something esle
}
Alternatively you can add this to the Date.prototype.
https://www.tutorialspoint.com/javascript/date_getday.htm

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();
}
}

Compare Current Day from encode string

I have json response which comes in different languages and I want to compare day; when I choose language Turkish it gets a response like:
sunday = {
day = Pazar;
timings = (
{
endTime = "23:59:00";
id = 100000174;
startTime = "11:58:00";
}
);
};
wednesday = {
day = "\U00e7ar\U015famba";
timings = (
{
endTime = "22:00:00";
id = 100000177;
startTime = "13:00:00";
}
);
};
I want to compare them the following way:
if(day.lowercased() == “\U00e7ar\U015famba”) {
//get Wednesday day
//this condition work in Sunday Dictionary
}
But It shows me error “Invalid escape sequence” and “closure expression is unused” Please see this image.
In Swift, hexadecimal value after the \u escape sequence needs to be enclosed in braces (with the \u as lowercase):
"\u{00e7}ar\u{015f}amba"
That's the reason for the error you're getting.
However, if you're comparing with the values returned from your JSON, which don't follow this format, you'll need to double-escape the \U to compare them as plain strings:
if day.lowercased() == "\\U00e7ar\\U015famba" {
...
}

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;
}