How can I compare the values from data Base to my current date ? A date is saved in the data base when some action is performed, I need to compare that date with my current date and do some action. How can I do that ?
The date is saved my date base in this format:
var tasksin2 : Task?
dateFormatter.dateFormat = "dd/MM/yyyy hh:mm"
let mydate="\(dateFormatter.string(from: datePicker.date))"
tasksin2?.time=mydate
(UIApplication.shared.delegate as! AppDelegate).saveContext()
Here ya go:
extension String {
func toDate() -> Date? {
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy hh:mm"
return formatter.date(from: self)
}
}
class MyViewController: UIViewController {
var dateString1: String!
var dateString2: String!
override func viewDidLoad() {
super.viewDidLoad()
// set dateStrings
printDateTypes()
}
func printDateTypes() {
guard let date1 = dateString1.toDate() else {
print("dateString1: \(dateString1) | Failed to cast to \"dd/MM/yyyy hh:mm\"")
return
}
guard let date2 = dateString2.toDate() else {
print("dateString2: \(dateString2) | Failed to cast to \"dd/MM/yyyy hh:mm\"")
return
}
let isDescending = date1.compare(date2) == ComparisonResult.orderedDescending
print("orderedDescending: \(isDescending)")
let isAscending = date1.compare(date2) == ComparisonResult.orderedAscending
print("orderedAscending: \(isAscending)")
let isSame = date1.compare(date2) == ComparisonResult.orderedSame
print("orderedSame: \(isSame)")
}
}
Related
I have a list of arrays that contains date object along with time, I have a record like in the this date format yyyy-MM-dd'T'HH:mm:ssZ I want to filter my array with ascending order and I also want to store unique values as in dates.
I am having record like 2021-04-01T11:00:00-04:00, 2021-04-01T12:00:00-04:00, 2021-04-02T09:00:00-04:00, 2021-04-02T10:00:00-04:00 and what I want 2021-04-01T11:00:00-04:00, 2021-04-02T09:00:00-04:00
Means before time value but only once. I have used this code but not working
let totalPods = [Items]
self.totalPods.sort { (firstItem, secondItem) -> Bool in
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" // "2021-04-01T11:00:00-04:00"
let firstDate = dateFormatter.date(from: firstItem.startDateString)
let secondDate = dateFormatter.date(from: secondItem.startDateString)
if let safeSecondDate = secondDate {
return firstDate?.compare(safeSecondDate) == .orderedAscending
}
return false
}
struct Items: Hashable {
let startDateString: String
}
let totalPods: [Items] = [Items(startDateString: "2021-04-01T11:00:00-04:00"),
Items(startDateString: "2021-04-01T12:00:00-04:00"),
Items(startDateString: "2021-04-02T09:00:00-04:00"),
Items(startDateString: "2021-04-02T10:00:00-04:00"),
Items(startDateString: "2021-04-01T11:00:00-04:00"),
Items(startDateString: "2021-04-01T11:00:00-04:00")]
// Store unique values
let uniqs = Array(Set(totalPods))
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
// filter by ASC
let sorted = uniqs.sorted { (item1, item2) in
dateFormatter.date(from: item1.startDateString)!.compare(dateFormatter.date(from: item2.startDateString)!) == .orderedAscending
}
// You can extend your model
extension Items {
var date: Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return dateFormatter.date(from: startDateString)!
}
}
// And sort like this
let sorted = uniqs.sorted { (item1, item2) in
item1.date.compare(item2.date) == .orderedAscending
}
import FSCalendar
import SwiftyJSON
import Alamofire
//import CalendarKit
import UIKit
struct PublicHoliday {
var name : String
var date : String
}
class ViewController: UIViewController, FSCalendarDelegate, FSCalendarDataSource {
#IBOutlet var calendar: FSCalendar!
#IBOutlet var contentsLabel: UILabel!
let formatter= DateFormatter()
var PH : [PublicHoliday]=[]
override func viewDidLoad() {
super.viewDidLoad()
calendarApi(year:"2020")
calendar.appearance.titleWeekendColor = UIColor.orange
calendar.allowsMultipleSelection = true
calendar.clipsToBounds = true
calendar.delegate = self
calendar.dataSource = self
}
func calendarApi(year:String){
let baseURLStr = "https://calendarific.com/api/v2/holidays"
let apiKey = "-------------------"
let urlStr = ["api_key":apiKey,"country":"KR","year":year]
//let urlStr = url + "api_key" +apiKey +"&country=KR"+"&year="+year
Alamofire.request(baseURLStr, method: .get, parameters: urlStr, encoding: URLEncoding.default).validate(statusCode:200..<300).responseJSON{
(response) in
switch response.result{
case .success(let value):
let jsonObject = JSON(value)
let count = jsonObject["response"]["PH"].count
for i in 0..<count {
let name = jsonObject["response"]["PH"][i]["name"].string!
let date = jsonObject["response"]["PH"][i]["date"]["iso"].string!
let ph = PublicHoliday(name: name, date: date)
self.PH.append(ph)
self.calendar.reloadData()
}
case .failure(_):
print("error")
}
}
}
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
formatter.dateFormat = "EEEE MM-dd-YYYY"
let string = formatter.string(from: date)
print("\(string)")
}
func calendar(_ calendar:FSCalendar, appearance:FSCalendarAppearance, fillDefaultColorFor date: Date)->UIColor?{
let dataForm = formatter.string(from:date)
for ph in self.PH{
if ph.date.compare(dataForm) == ComparisonResult.orderedSame{
return UIColor.cyan
}
}
return nil
}
func calendar(_ calendar: FSCalendar, subtitleFor date: Date) -> String? {
let dataForm = formatter.string(from: date)
for ph in self.PH{
if ph.date.compare(dataForm) == ComparisonResult.orderedSame{
return ph.name
}
}
return nil
}
}
In these two methods,
func calendar(_ calendar:FSCalendar, appearance:FSCalendarAppearance, fillDefaultColorFor date: Date)->UIColor?{
let dataForm = formatter.string(from:date)
for ph in self.PH{
if ph.date.compare(dataForm) == ComparisonResult.orderedSame{
return UIColor.cyan
}
}
return nil
}
func calendar(_ calendar: FSCalendar, subtitleFor date: Date) -> String? {
let dataForm = formatter.string(from: date)
for ph in self.PH{
if ph.date.compare(dataForm) == ComparisonResult.orderedSame{
return ph.name
}
}
return nil
}
You are comparing the string representations of the dates from the data source PH and the date parameter supplied by the datasource/delegate method of FSCalendar. However, you did not set a correct format (or any format at all, actually) for the formatter to use. This causes formatter.string(from:) to produce empty strings, so you are comparing empty strings with actual dates like 2020-12-25. From a brief look of the API documentation of the API that you are using, it seems like the dates come in the ISO 8601 local date format.
You should therefore, set a format like this:
func calendar(_ calendar:FSCalendar, appearance:FSCalendarAppearance, fillDefaultColorFor date: Date)->UIColor?{
formatter.dateFormat = "yyyy-MM-dd"
let dataForm = formatter.string(from:date)
for ph in self.PH{
if ph.date == dataFrom {
return UIColor.cyan
}
}
return nil
}
func calendar(_ calendar: FSCalendar, subtitleFor date: Date) -> String? {
formatter.dateFormat = "yyyy-MM-dd"
let dataForm = formatter.string(from: date)
for ph in self.PH{
if ph.date == dataFrom {
return ph.name
}
}
return nil
}
An even better approach would be to use Date in your data source directly:
struct PublicHoliday {
var name : String
var date : Date
}
And parse it when you get the response:
let dateString = jsonObject["response"]["PH"][i]["date"]["iso"].string!
formatter.dateFormat = "yyyy-MM-dd"
let date = formatter.date(from: dateString)!
let ph = PublicHoliday(name: name, date: date)
This way you can compare ph.date directly with the date supplied by FSCalendar.
How do I format this date so that it is readable. I want it to show for example: "January 7th, 2018 7:30am". I tried to look at other answers but wasn't sure where to add the extension.
let date = Date(timeIntervalSince1970: request.timestamp / 1000)
dateCell.textLabel?.text = date.description
class Request {
var key:String
var sender:String
var recipient:String
var name:String
var location:String
var when:String
var whereStr:String
var message:String
var timestamp:Double
var status:String
init(dict: [String: Any]) {
self.key = dict["key"] as? String ?? ""
self.sender = dict["sender"] as? String ?? ""
self.recipient = dict["recipient"] as? String ?? ""
self.name = dict["name"] as? String ?? ""
self.location = dict["location"] as? String ?? ""
self.when = dict["when"] as? String ?? ""
self.whereStr = dict["where"] as? String ?? ""
self.message = dict["message"] as? String ?? ""
self.timestamp = dict["timestamp"] as? Double ?? 0.0
self.status = dict["status"] as? String ?? ""
}
Try This
func getCurrentDateTimeFromTimeStamp(timeStapm:String)->String{
let date = NSDate(timeIntervalSince1970:Double(timeStapm)!/1000)
let formatter = DateFormatter()
formatter.dateFormat = "MMMM d, yyyy HH:mm a"
return formatter.string(from: date as Date)
}
pass timestamp and get as date in string format as per your requirement just pass dateFormat.
use like this
dateCell.textLabel?.text = self.getCurrentDateTimeFromTimeStamp(timeStapm:"pass your timestamp")
You should use DateFormatter:
let formatter = DateFormatter()
formatter.format = "MMMM d, yyyy HH:mm a"
let dateString = formatter.string(from: date)
Use a dateFormatter object to style the date however you want
let format = DateFormatter()
format.format = "MM/dd/yyyy"
//get your date in string like this
let dateInString = format.string(from: date)
// this will give you "10/02/2018"
You can visit date format examples to see different format and how to get them.
You can add extension anywhere in the app and one (same name) extension for comlpete app. look below
import UIKit
class ViewControllerHellBoy: UIViewController
{
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
dateCell.textLabel?.text = self.userFriendlyFullDate()
}
}
extension Date: Dateable {
var formatter: DateFormatter { return DateFormatter() }
/** Return a user friendly hour */
func userFriendlyFullDate() -> String {
// Customize a date formatter
formatter.dateFormat = ""MMMM d, yyyy HH:mm a"" //Use format you want to
formatter.timeZone = TimeZone(abbreviation: "UTC") . // Time zone you wishes to provide
return formatter.string(from: self)
}
That is how you can use extensions. You can also create separate class and keep all extensions there.
How to display events on Fscalender?
This is my code to fetch events from api call.
func SetUpUIDashBoardCalenderdata()
{
APIManager.sharedInstance.FetchParentDashboardCalenderDataFromURL(){(dashBoardCalenderJson)-> Void in
let calenderVar = JSON(dashBoardCalenderJson)
print("calenderVar----",calenderVar)
let info = calenderVar["dates"].rawString()
let jsonData = info?.data(using: .utf8)!
let dictionary = try? JSONSerialization.jsonObject(with: jsonData!, options: []) as! Array<Any>
print("dictionary",dictionary)
}
}
You should implement FSCalendarDataSource protocol.
please take a look at my example :
let events = [Date]()
fileprivate lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd"
return formatter
}()
func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
let dayFormatted = dateFormatter.string(from: date)
var counter = 0
for event in events{
let day = dateFormatter.string(from: event)
if dayFormatted == day{
counter += 1
}
}
return counter
}
or shorter :
func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
let dayFormatted = dateFormatter.string(from: date)
return events.filter({ dateFormatter.string(from: $0) == dayFormatted }).count
}
I am try to compare two date-
dateArrayForCompare, is the date which i get from NSDate and, dateArrayServer, is the date which i get from json response.
var dateArrayServer = NSMutableArray()
var dateArrayCalendar = NSMutableArray()
var dateArrayForCompare = NSMutableArray()
let dateHomework:NSArray = allAsign.valueForKey("date") as! NSArray
let homeWork = allAsign.valueForKey("assignmenttype") as! NSArray
for date in dateHomework{
self.dateArrayServer.addObject(date as! String)
}
let sys_date = NSDate()
print("System Date: \(sys_date)")
let df = NSDateFormatter()
df.dateFormat = "dd-MM-yyyy"
let currentDate = df.stringFromDate(sys_date)
print("String Date: \(currentDate)")
for dt in 0...self.dateArrayServer.count-1
{
if(self.dateArrayServer.objectAtIndex(dt) .isEqualToString("\(self.dateArrayForCompare)"))
{
print("Assignment on date: \(self.dateArrayServer.objectAtIndex(dt)) are:\n\(allAsign.objectAtIndex(dt))")
}else
{
print("\(self.dateArrayServer.objectAtIndex(dt)) doesn't match with \(self.dateArrayForCompare) ")
}
}
But get this result-
Something like this (swift 2.2)
for dt in 0 ... dateArrayServer.count-1
{
let date1 = dateArrayServer.objectAtIndex(dt) as! String
for value in dateArrayForCompare.enumerate() {
if date1 == value.element as! String {
print(date1)
}
}
}