Compare dates from given array and two date ranges swift - swift

Hi I have a problem scenario with date comparison with given date range the scenario is as follows:
I have an array containing data:
var filter1Date = [String]()
filter1Date[Wed, 06 May 2015 03:44:19 GMT, Wed, 06 May 2015 03:36:27 GMT, Wed, 06 May 2015 02:56:51 GMT, Wed, 06 May 2015 01:54:25 GMT, Tue, 05 May 2015 19:17:18 GMT, Wed, 06 May 2015 02:57:59 GMT, Wed, 06 May 2015 02:07:38 GMT, Wed, 06 May 2015 01:53:14 GMT, Tue, 05 May 2015 14:30:10 GMT, Tue, 05 May 2015 14:04:34 GMT]
Now I have two dates which gives from and to two dates
example:
var fromDate = "dd-MM-yyyy"
var toDate = "dd-MM-yyyy"
now I want to compare array of filter1Date variable with range fromDate and toDate variable
from this I have to get data from filter1Date which ranges in between these dates can anybody help me in this?

To compare two NSDates you can use NSDate.compare() method. I wrote an extension for the NSDate to handle this:
extension NSDate
{
func isInRange(from: NSDate, to:NSDate) -> Bool
{
if(self.compare(from) == NSComparisonResult.OrderedDescending || self.compare(from) == NSComparisonResult.OrderedSame)
{
if(self.compare(to) == NSComparisonResult.OrderedAscending || self.compare(to) == NSComparisonResult.OrderedSame)
{
// date is in range
return true
}
}
// date is not in range
return false
}
}
You can then use it like this:
var dates:[NSDate] = ... // your dates array
var startDate:NSDate // your start range date
var endDate:NSDate // your end range date
for date in dates
{
if(date.isInRange(startDate, to: endDate))
{
//date is in range, do something
}
else
{
//date is not in range
}
}

Related

How can compare Date on mongo without time?

This is a sample data
[{ date: '2020-05-21T14:02:00.0123 }, { date: '2020-05-22T14:02:00.0123 }, { date: '2020-05-23T14:02:00.0123 }]
I want to filter records of 22-May or earlier, here is my expected:
[{ date: '2020-05-21T14:02:00.0123 }, { date: '2020-05-22T14:02:00.0123 }]
I tried with this query:
{ date: { $lte: new Date('2020-05-22') }}
But it returns only data earlier 22-May. I think problem is { date: { $lte: new Date('2020-05-22') }} will data.date lte 2020-05-22T00:00:00.000
How I can exclude time ?
You need to match type of input with type of date field in document, either both should be Date's or strings. I would highly suggest maintain dates as dates in DB. Also you need to know that dates in MongoDB are of format ISODate() and holds UTC date.
If your DB date field is of type date :
I want to filter records of 22-May or earlier
As you wanted to get documents <= 22-May, then sending new Date('2020-05-22') doesn't work. Cause :
when you do new Date('2020-05-22'), it will give you Fri May 22 2020 00:00:00 GMT only if you belong to UTC, for example if you're in New York America which is 4 hours behind UTC then it would result in Thu May 21 2020 20:00:00 GMT-0400 (Eastern Daylight Time) which represents EDT, basically it's your system/app server time i.e; local date time.
So if your region is behind UTC then you'll get a back date Thu May 21 2020 otherwise if it's ahead of UTC then there is no issue you'll see Fri May 22 2020.
Ok, now that we've fixed date issues, but we need to look into hours now :
Since you want docs <= 22-May then Fri May 22 2020 00:00:00 GMT doesn't work you need to have either <= Fri May 22 2020 23:59:59 GMT or Sat May 23 2020 00:00:00 GMT. In order to get that :
let date = new Date('2020-05-22')
date.setDate(date.getUTCDate()); // Setting utc date, Only useful if you're region is behind UTC
date = new Date(date.setHours(23,59,59,999)) // This overrides hours generated with 23:59:59 - which is what exactly needed here.
/** Now do your query */
{ date: { $lte: date }}
If your DB date field is of type string :
Then you don't need to convert string to date, instead you can send input date in string format :
let date = new Date('2020-05-22').toISOString() // 2020-05-22T00:00:00.000Z
/** Above would get you an ISO string no matter which region you're in, 
* now since we need `2020-05-22T23:59:59.000Z` which is not easy on ISO string
* We would just do +1 on date like `new Date('2020-05-23').toISOString()` - // 2020-05-23T00:00:00.000Z */
let date = new Date('2020-05-23').toISOString(); // like this
date = date.slice(0, -1) // removing `Z` from date string as your `date` field doesn't have this.
// Now your query is just `$lt`
{ date: { $lt: date }}
Test : mongoplayground

How to get current month from the selected date in GWT?

Date startDate = new Date(Long.valueOf(""05/07/2018")getValue().toString());
get last day of selected month is required
private Date lastDayOfMonth(Date month) {
Date lastDay = (Date) month.clone();
CalendarUtil.addMonthsToDate(lastDay, 1);
CalendarUtil.setToFirstDayOfMonth(lastDay);
CalendarUtil.addDaysToDate(lastDay, -1);
GWT.log("lastDay :: "+lastDay);
return lastDay;
}
I get lastDay :: Tue Jul 31 00:00:00 GMT+530 2018
But i get 30th instead of 31st
First, your code does not work
Date startDate = new Date(Long.valueOf(""05/07/2018")getValue().toString());
Second, your method private Date lastDayOfMonth(Date month) looks fine, I have a test and got result Tue Jul 31 00:00:00
I dont understand your problem "Tue Jul 31 00:00:00 GMT+530 2018 But i get 30th instead of 31st". How can you get 30th from Tue Jul 31 00:00:00 GMT+530?

Date minus date is not giving desired answer - IONIC 2

When I try to subtract
Wed Dec 06 2017 15:58:59 GMT+0530 (India Standard Time) minus Tue Nov 28 2017 00:00:00 GMT+0530 (India Standard Time) , the answer which is coming is -22
But the answer should be 6
What is going wrong and where, below is my page.ts code:
this.tt = new Date();
this.tt1 = this.datePipe.transform(this.tt,'dd/mm/yyyy');
console.log(this.ent[0],"server DATE");
// in console we see this - 28-NOV-17 server DATE
var firstDate= new Date(this.ent[0]); //Jan 01 2017 00:00:00
var secondDate = new Date();//Jan 04 2017 00:00:00
console.log(firstDate);
// answer in console - Tue Nov 28 2017 00:00:00 GMT+0530 (India Standard Time)
console.log(secondDate);
//answer in console - Wed Dec 06 2017 15:58:59 GMT+0530 (India Standard Time)
console.log(secondDate.getDate() - firstDate.getDate() );
//answer in console - -22
Date.getDate() gives the "dd" of the date (in your case 6 and 28 which explains the result being -22).
I'm a bit confused with the expected result being 6. So maybe my answer won't fit you. What I would do however is convert the date in time, do the substraction and convert it back to number of days.
So
Math.Floor((secondDate.getTime() - firstDate.getTime()) / 86400000);
(86400000 being 1000 (milliseconds) * 3600 (seconds in an hour) * 24 (number of hours in a day)
you can convert both dates to timestamp and subtract the timestamp you will get the result days in millis now convert it to days
getTimestamp(dateParam:string):string{
var date = new Date(dateParam); // some mock date
var milliseconds = date.getTime();
return milliseconds.toString();
}
var one_day=1000*60*60*24;
console.log(Math.ceil(getTimestamp(secondDate) - getTimestamp(firstDate))/(one_day) );

Go language time.Parse() for timestamps with no timezone

In Go I'm trying to use the time.Parse() function from the time package to convert a string timestamp into a Time object. I know Go has an uncommon way of representing the time format your timestamps are in by providing it with an example of how their reference time (Mon Jan 2 15:04:05 -0700 MST 2006) would be displayed in your format. I'm still having issues with errors however. Here is an example of one of my timestamps:
Tue Nov 27 09:09:29 UTC 2012
Here is what the call I'm making looks like:
t, err := time.Parse("Mon Jan 02 22:04:05 UTC 2006", "Tue Nov 27 09:09:29 UTC 2012")
So basically what I've done here is try and match the formatting for day name/month name/day number, the hour/minute/second format, the string literal "UTC" and the year format. Note that I've increased the hours field of the Go reference format by 7 (from 15 to 22) to account for the fact that their timestamp is in a negative 7 timezone and all my timestamps are in a UTC timezone.
The error I get is:
parsing time "Tue Nov 27 09:09:29 UTC 2012" as "Mon Jan 02 22:04:05 UTC 2006": cannot parse ":09:29 UTC 2012" as "2"
What am I doing wrong here? Am I misinterpreting how to use time.Parse() or is my use case not supported for some reason?
Your format string should be:
Mon Jan 02 15:04:05 MST 2006
playground
That is, use MST for the timezone and 15 for the hour, as documented in your linked Parse function.
In this case, you can use time.UnixDate:
package main
import (
"fmt"
"time"
)
func main() {
t, e := time.Parse(time.UnixDate, "Tue Nov 27 09:09:29 UTC 2012")
if e != nil {
panic(e)
}
fmt.Println(t)
}
https://golang.org/pkg/time#UnixDate

How to parse these time zones with NSDateFormatter?

I'm parsing a large number of internet dates. First I try a formatter with en_US_POSIX locale, then with en_GB. The code looks more or less like this:
{
NSDate *date = [dateString dateWithDateFormat:#"EEE, dd MMM yyyy HH:mm:ss z (zzz)" localeIdentifier:#"en_US_POSIX"];
if (date) return date;
date = [dateString dateWithDateFormat:#"EEE, dd MMM yyyy HH:mm:ss z (zzz)" localeIdentifier:#"en_GB"];
return date;
}
- (NSDate*) dateWithDateFormat:(NSString*)dateFormat localeIdentifier:(NSString*)localeIdentifier
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];
formatter.dateFormat = dateFormat;
[formatter dateFromString:self];
}
However, date strings with the following time zones fail to parse:
Mon, 16 Jul 2012 12:08:17 +0100 (GMTUK)
Thu, 6 Sep 2012 13:00:06 +0900 (KST)
Wed, 3 Nov 2010 10:12:15 +0100 (Hora est�ndar romance)
Wed, 14 Sep 2011 14:37:35 +0100 (IST)
Wed, 2 May 2012 09:41:06 +0200 (MEST)
Sun, 31 Oct 2010 12:53:06 +0800 (SGT)
Thu, 19 Jan 2012 08:34:44 -0300 (UYT)
What am I doing wrong?
Should I pre-process the strings to remove the time zone parenthesis in these cases only?
NSDate can store a point in time without timezone information. It's up to your software to know whether a specific NSDate instance stores the point in time in UTC or in the local time zone. In most cases, you want to use UTC dates.
Because of that, it's important to handle time zone differences when parsing the dates. But it's not possible to remember the time zone the dates was originally in (at least not with an NSDate instance only).
So I would recommend that you cut off the time zone in parenthesis and just parse the numerical time zone offset before it. That way, you can convert all strings into an NSDate instance in UTC and you shouldn't have any problems parsing the strings.
And shouldn't the date fromat be (i.e. uppercase Z for a numeric time zone offset)?
#"EEE, dd MMM yyyy HH:mm:ss ZZZ"