how to compare date in swift 3.0? - swift3

I have two dates and I want to compare it.
How can I compare dates?
I have to date objects. Say modificateionDate older updatedDate.
So which is the best practice to compare dates?

Date now conforms to Comparable protocol. So you can simply use <, > and == to compare two Date type objects.
if modificateionDate < updatedDate {
//modificateionDate is less than updatedDate
}

Per #NiravD's answer, Date is Comparable. However, if you want to compare to a given granularity, you can use Calendar's compare(_:to:toGranularity:)
Example…
let dateRangeStart = Date()
let dateRangeEnd = Date().addingTimeInterval(1234)
// Using granularity of .minute
let order = Calendar.current.compare(dateRangeStart, to: dateRangeEnd, toGranularity: .minute)
switch order {
case .orderedAscending:
print("\(dateRangeEnd) is after \(dateRangeStart)")
case .orderedDescending:
print("\(dateRangeEnd) is before \(dateRangeStart)")
default:
print("\(dateRangeEnd) is the same as \(dateRangeStart)")
}
> 2017-02-17 10:35:48 +0000 is after 2017-02-17 10:15:14 +0000
// Using granularity .hour
let order = Calendar.current.compare(dateRangeStart, to: dateRangeEnd, toGranularity: .hour)
> 2017-02-17 10:37:23 +0000 is the same as 2017-02-17 10:16:49 +0000

Swift iOS 8 and up When you need more than simply bigger or smaller date comparisons. For example is it the same day or the previous day,...
Note: Never forget the timezone. Calendar timezone has a default, but if you do not like the default, you have to set the timezone yourself. To know which day it is, you need to know in which timezone you are asking.
extension Date {
func compareTo(date: Date, toGranularity: Calendar.Component ) -> ComparisonResult {
var cal = Calendar.current
cal.timeZone = TimeZone(identifier: "Europe/Paris")!
return cal.compare(self, to: date, toGranularity: toGranularity)
}
}
Use it like this:
if thisDate.compareTo(date: Date(), toGranularity: .day) == .orderedDescending {
// thisDate is a previous day
}
For a more complex example how to use this in a filter see this:
https://stackoverflow.com/a/45746206/4946476

Swift has ComparisonResult with orderedAscending, orderedDescending and same as below.
if modificateionDate.compare(updatedDate) == ComparisonResult.orderedAscending {
//Do what you want
}
Hope this may help you.

Related

How to check the date part in a Java collection Arraylist?

I have one ArrayList:
List<Date> date= ArrayList<Date>();
date.add(2017-07-26 09:27:33);
date.add(2017-07-28 10:11:33);
date.add(2017-07-25 08:27:33);
date.add(2017-07-25 07:27:33);
Now I am testing
date.contains(2017-07-25 11:27:33); //should come true
I want to check on the basis only the only date not time. How can I check only base of date not time?
First of all your code can not compile.
Lets change it to valid java code and compare two date only without time portion:
List<Date> date = new ArrayList();
DateFormat format = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss", Locale.ENGLISH);
DateFormat compareFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
try {
date.add(format.parse("2017-07-26 09:27:33"));
date.add(format.parse("2017-07-28 10:11:33"));
date.add(format.parse("2017-07-25 08:27:33"));
date.add(format.parse("2017-07-25 07:27:33"));
Date searchedDate = format.parse("2017-07-26 16:27:33");
boolean isExist = date.stream().anyMatch(d -> compareFormat.format(d).equals(compareFormat.format(searchedDate)));
System.out.println(isExist);
} catch (ParseException e) {
e.printStackTrace();
}
Also there are another solutions to compare date without time part, take a look another solutions : How to compare two Dates without the time portion?

iOS-NSArray filter having condition

I'm new here!
I have an NSArray like this ("file01_header","file01_body", "file01_xxx", ... ,"file02_header", ...).
I filter it and get 2 distinct NSArrays:
Array_header ("file01_header","file02_header",...)
Array_body
("file01_body", "file02_body", ...)
now I have to subtract from Array_header all the items that have a corresponding one in Array_body, because not all items have a fileNN_body for the fileNN_header in the original array, and I have to give the Array_header as output with only items that has no corresponding body.
How can I do this?
Thanks!!
If you're using swift you can filter pretty easily using a closure and some minor string-fu.
Here's an example:
let funkyArray = ["file01_header","file01_body", "file01_xxx", "file02_header","file03_xxx"]
let headerFilterClosure : (String) -> Bool = {fileName in
if fileName.containsString("header") {
let fileBase = fileName.componentsSeparatedByString("_")[0]
let fileBodyName = "\(fileBase)_body"
if funkyArray.contains(fileBodyName) {
return true
}
}
return false
}
funkyArray.filter(headerFilterClosure)
I think a better long term solution would be to not have such a funky array and use a data structure or at least a tuple with options to manage your file info.
Best,
Josh

Replace the jquery datepicker dateFormat with momentjs parsing and format

For the sake of consistency I would like to be able to switch the parsing/formatting of JQuery UI's datepicker to use momentjs instead. Any thoughts on what might be the best way to do this?
So far the best method that I've found to do this is to override the global jquery-ui parseDate and formatDate functions like so:
$.datepicker.parseDate = function(format, value) {
return moment(value, format).toDate();
};
$.datepicker.formatDate = function (format, value) {
return moment(value).format(format);
};
Then this nicely allows you to use the usual syntax for attaching a datepicker to a field but the format you specify will instead refer to a momentjs format instead http://momentjs.com/docs/#/parsing/string-format/
$(".selector").datepicker({ dateFormat: "MM-DD-YYYY" });
If anyone using https://xdsoft.net/jqplugins/datetimepicker plugin and facing the same issue, the first solution will be your take.
After using the accepted solution you will face selected date doesn't highlighted the issue.
So modifying accepted solution to fix selected date highlight issue
jQuery.datetimepicker.setDateFormatter({
parseDate: function (date, format) {
var d = moment(date, format);
return d.isValid() ? d.toDate() : false;
},
formatDate: function (date, format) {
if (format == "Y/m/d")
return moment(date).year() + "/" + moment(date).month() + "/" + moment(date).date();
return moment(date).format(format);
}
});

Replicating Google Analytics DateRange picker

I need to replicate the Google Analytics date picker (plus a few new options). Can anyone tell me how to highlight all the cells on a calendar between two dates. My basic JavaScript is OK but I think I'm getting a bit out of my depth.
I'm using JQuery 1.5.1 and JQuery UI 1.8.14.
In needed to replicate Google Analytics date picker as well. I know you were asking just about highlighting cells, but if someone else would prefer complete solution, you can see my answer from another question: jquery google analytics datepicker
Here's a solution using the built-in 'onSelect' event (jsFiddle):
$(document).ready(function() {
'use strict';
var range = {
'start': null,
'stop': null
};
$('#picker').datepicker({
'onSelect': function(dateText, inst) {
var d, ds, i, sel, $this = $(this);
if (range.start === null || range.stop === null) {
if (range.start === null) {
range.start = new Date(dateText);
} else {
range.stop = new Date(dateText);
}
}
if (range.start !== null && range.stop !== null) {
if ($this.find('td').hasClass('selected')) {
//clear selected range
$this.children().removeClass('selected');
range.start = new Date(dateText);
range.stop = null;
//call internal method '_updateDatepicker'.
inst.inline = true;
} else {
//prevent internal method '_updateDatepicker' from being called.
inst.inline = false;
if (range.start > range.stop) {
d = range.stop;
range.stop = range.start;
range.start = d;
}
sel = (range.start.toString() === range.stop.toString()) ? 0 : (new Date(range.stop - range.start)).getDate();
for (i = 0; i <= sel; i += 1) {
ds = (range.start.getMonth() + 1).toString() + '/' + (range.start.getDate() + i).toString() + '/' + (range.start.getFullYear()).toString();
d = new Date(ds);
$this.find('td a').filter(function(index) {
return $(this).text() === d.getDate().toString();
}).parents('td').addClass('selected');
}
}
}
}
});
});
I became desperate and came up with a solution on my own. It wasn't pretty but I'll detail it.
I was able to construct a div that had the text boxes, buttons and the datepicker that looked like the Google Analytics control but I couldn't make the datepicker work properly. Eventually, I came up with the idea of creating a toggle variable that kept track of which date you were selecting (start date or end date). Using that variable in a custom onSelect event handler worked well but I still couldn't figure out how to get the cells between dates to highlight.
It took a while, but I slowly came to the realization that I couldn't do it with the datepicker as it existed out of the box. Once I figured that out, I was able to come up with a solution.
My solution was to add a new event call afterSelect. This is code that would run after all the internal adjustments and formatting were complete. I then wrote a function that, given a cell in the datepicker calendar, would return the date that it represented. I identified the calendar date cells by using jQuery to find all the elements that had the "ui-state-default" class. Once I had the date function and a list of all the calendar cells, I just needed to iterate over all of them and, if the date was in the correct range, add a new class to the parent.
It was extremely tedious but I was able to make it work.

Get the first day of week of a year (any programming language)

How can I get the first day of the week of any given year (day being 1 to 7, or weekday name)?
I tried to figure it out in JavaScript, but I accept any other language.
I need to select a year to later build the full calendar (I thought using HTML tables and JavaScript), and for that I need to know at least the first day of the selected year.
I haven't found a solution or a question specifically dealing with finding the first day of any given year such that you only need to pass 1995, 2007, 1891. So if it's a repeated question please point the solution.
Do you have at least an online chart or DHTML site where I can see any full calendar for any year visually in that way?
In Javascript you can use this:
getWeekDay = function (year) {
var d = new Date();
d.setFullYear(year,0,1);
return d.getDay()+1;
};
document.write(getWeekDay(2011));
Result is 1..7, as requested.
At this Wikipedia article, look for Sakamoto's algorithm.
Pretty easy with C# and .NET:
using System;
public class SomeClass
{
public static void Main()
{
DateTime dt = new DateTime(2000,1,1);
Console.WriteLine(dt.DayOfWeek);
dt = new DateTime(2010,1,1);
Console.WriteLine(dt.DayOfWeek);
}
}
Output:
Saturday
Friday
The Java version:
import java.util.Date;
import java.util.GregorianCalendar;
public class test3
{
public static void main (String[] args)
{
GregorianCalendar c = new GregorianCalendar(2000,1,1);
Date d = c.getTime();
System.out.println(d.getDay());
c = new GregorianCalendar(2010,1,1);
d = c.getTime();
System.out.println(d.getDay());
}
}
Output:
2
1
With .NET's BCL:
return new DateTime(year, 1, 1).DayOfWeek; // DayOfWeek enum value
In Noda Time:
return new LocalDate(year, 1, 1).IsoDayOfWeek; // IsoDayOfWeek enum value
In Java using the built-in classes:
Calendar calendar = Calendar.getInstance();
calendar.set(year, 1, 1);
return calendar.get(Calendar.DAY_OF_WEEK); // 1 (Sunday) - 7 (Saturday)
In Java using Joda Time:
return new LocalDate(year, 1, 1).getDayOfWeek(); // 1 (Monday) - 7 (Sunday)
This site http://5dspace-time.org/Calendar/Algorithm.html
has a good explanation on how to calculate it even with pencil-and-paper
Wikipedia explains it too