UICalendar calendarView.reloadDecorations got error - swift5

I followed the "Display decorations for specific dates" in Apples UICalendar documentation . https://developer.apple.com/documentation/uikit/uicalendarview
Please give me your advices.
The following is my code.
func reloardCalendarDecorations(){
var dateComponents : [DateComponents] = []
for event in appdelegate.eventsByMonth{
var dateS :String = event["start"] as! String
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd HH:mm"
let date = dateFormatter.date(from: dateS)
print("date ",date!)
let calendar = Calendar(identifier: .gregorian)
let timeZone = TimeZone.current
/// convert to dateComponents from date
let components = calendar.dateComponents(in: timeZone, from: date!)
print("components",components)
dateComponents.append(components)
}
calendarView.reloadDecorations(forDateComponents: dateComponents, animated: true)
/// got error
/// Value of type '(UICalendarView, DateComponents) -> UICalendarView.Decoration?' has no member 'reloadDecorations'
}
Please advise me how to use reloadDecorations.
Thank you.

Related

Creating Date object from timestamp in Swift [duplicate]

I get a crash when running and it points at the dateFormmater.timezone.
The error in the console is:
Could not cast value of type 'Swift.Optional' (0x1192bf4a8) to 'NSTimeZone' (0x1192c0270).
the value of rowEvents.date is "1480134638.0"
Im trying to pull out a Unix timestamp from Firebase saved as a string. Convert it to Date and again save it as a string so I can post it on a cell label.
I got this code from StackOverflow. I plugged in my data and everything is all good until I run it. I guess everything is not all good...
if let lastUpdated : String = rowEvents.date {
let epocTime = TimeInterval(lastUpdated)! / 1000 // convert it from milliseconds dividing it by 1000
let unixTimestamp = NSDate(timeIntervalSince1970: epocTime) //convert unix timestamp to Date
let dateFormatter = DateFormatter()
dateFormatter.timeZone = NSTimeZone() as TimeZone!
dateFormatter.locale = NSLocale.current // NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
dateFormatter.date(from: String(describing: unixTimestamp))
let updatedTimeStamp = unixTimestamp
let cellDate = DateFormatter.localizedString(from: updatedTimeStamp as Date, dateStyle: DateFormatter.Style.full, timeStyle: DateFormatter.Style.medium)
cell.subtitleLabel.text = cellDate
}
The result came from this code here:
let myTimeStamp = self.datePicker?.date.timeIntervalSince1970
let calendarDate = String(describing: myTimeStamp! /** 1000*/)
You can convert unixTimestamp to date using Date(timeIntervalSince1970:).
let unixTimestamp = 1480134638.0
let date = Date(timeIntervalSince1970: unixTimestamp)
If you want to display date in string with specific formate than you can use DateFormatter like this way.
let date = Date(timeIntervalSince1970: unixtimeInterval)
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "GMT") //Set timezone that you want
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" //Specify your format that you want
let strDate = dateFormatter.string(from: date)
The problem is the line dateFormatter.timeZone = NSTimeZone() as TimeZone!.
Simply use TimeZone instead of NSTimeZone like
dateFormatter.timeZone = TimeZone.current and your code will work.
You might also remove your / 1000 because 1480134638.0 looks more like seconds than milliseconds (since 1970).
Swift 4.1. I created a function. Just pass you timeStamp in function param and function will return data in string data type. You can add more properties to DateFormatter object.
func getDateFromTimeStamp(timeStamp : Double) -> String {
let date = NSDate(timeIntervalSince1970: timeStamp / 1000)
let dayTimePeriodFormatter = DateFormatter()
dayTimePeriodFormatter.dateFormat = "dd MMM YY, hh:mm a"
// UnComment below to get only time
// dayTimePeriodFormatter.dateFormat = "hh:mm a"
let dateString = dayTimePeriodFormatter.string(from: date as Date)
return dateString
}
Using playground all I did was this.
let epochTime = 1547855446
let newTime = Date(timeIntervalSince1970: TimeInterval(epochTime))
print(newTime)
Returns this - 2019-01-18 23:50:46 +0000
extension Double{
func convertDate(formate: String) -> String {
let date = (timeIntervalSince1970: self)
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.locale = NSLocale(localeIdentifier: "(your localization language)" ) as Locale //localization language
dateFormatter.dateFormat = formate //Specify your format that you want let
strDate = dateFormatter.string(from: date)
return strDate
}
}
//usage
let timeStamp:Double = Double(1595407043)
print(timeStamp.convertDate(formate: "EEEE dd/MM/YYY"))
This solution is valid for swift 3 -> 4.2 :
you can add an extension on the Double that returns the date formatted:
extension Double {
// returns the date formatted.
var dateFormatted : String? {
let date = Date(timeIntervalSince1970: self)
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.none //Set time style
dateFormatter.dateStyle = DateFormatter.Style.short //Set date style
return dateFormatter.string(from: date)
}
// returns the date formatted according to the format string provided.
func dateFormatted(withFormat format : String) -> String{
let date = Date(timeIntervalSince1970: self)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: date)
}
}
example on the above :
let timeStamp = 82749029.0
print(timeStamp. dateFormatted)
//output
//12/11/1994
let timeStamp = 82749029.0
print(timeStamp. dateFormatted(withFormat : "MM-dd-yyyy HH:mm"))
//output
//12-11-1994 13:04

SwiftUI string to formatted date (ISO)

can you please help me with that topic?
from the API i get the following date as a string: 2021-05-21T14:35:15.647+02:00
How can i convert this to a date object, so that i can format it?
I tried it in different ways as subscribed here in stackoverflow or in other tutorials, like this:
let date = "2021-05-21T14:35:15.647+02:00"
func formatStringDate(date: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let newDate = dateFormatter.date(from: date)
dateFormatter.setLocalizedDateFormatFromTemplate("MMMM d, yyyy")
return dateFormatter.string(from: newDate!)
}
var newDate = formatStringDate(date: date)
print(newDate)
or
let timestampString = "2018-12-09T11:08:48-05:00"
if let date = isoDateFormatter.date(from: timestampString) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM, dd, yyyy h:mm a"
let dateFormattedString = dateFormatter.string(from: date)
print(dateFormattedString) // December, 09, 2018 11:08 AM
} else {
print("not a valid date")
}
But it´s not working.
Thanks for your help
Thanks for your help, i got the following snippet to work:
let dateString = "2021-05-21T14:35:15.647+02:00"
let inputFormatter = ISO8601DateFormatter()
inputFormatter.formatOptions = [
.withFractionalSeconds,
.withFullDate
]
let date = inputFormatter.date(from: dateString)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.YYYY"
print(dateFormatter.string(from: date!))
Thanks

swift 4 Date from from ISO string to custom format?

I have ISO date from API I want to convert it to another custom date format, I've checked some threads here it's look like I have to use the extension on Date class, unfortunately, all my attempts failed.
this example for date i have :
2014-10-22T00:00:00+00:00
I want to convert it to July 2014
can I use normal Date class to do it?
and below what I am trying to do
let formatter = ISO8601DateFormatter()
let date = formatter.date(from: "2016-08-26T12:39:00Z")
let string = formatter.string(from: Date())
Try it:
let formatter = ISO8601DateFormatter()
if let date = formatter.date(from: "2014-10-22T00:00:00+00:00") {
let string = date.stringDate
print(string) // October 2014
}
extension Date {
var stringDate: String {
let formatter = DateFormatter()
formatter.dateFormat = "MMMM yyyy"
return formatter.string(from: self)
}
}
my Date load from SQL Server and format like this "2018-01-17T03:08:28.158769" the code below is work for me perfectly
let isoDate = "2018-01-17T03:08:28.158769"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
let date = dateFormatter.date(from:isoDate!)!
dateFormatter.dateFormat = "d.MMMM.YYYY"
let displayDate = dateFormatter.string(from: date)
displayDateInLabel.text = displayDate
result
17.January.2018
You can get Month and Year like this
override func viewDidLoad() {
super.viewDidLoad()
print(getFormattedDate(date: Date()))
}
func getFormattedDate(date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM YYYY"
let strMonth = dateFormatter.string(from: date)
return strMonth
}

Convert facebook birthday to age swift

When retrieving birthday from the Facebook SDK i get this string "01/12/1990".
My question is, how would you convert the birthday into the age of the user using this string?
Swift 4
My use case is also for Facebook and I have used UserDefaults to store the birthdate. The below function will retrieve birthdate from UserDefaults, as returned by the graphRequest which is in the same format as your Date. The function will return an Integer with the user's age.
func getAgeFromBirthdate() -> Int {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let birthday = UserDefaults.standard.object(forKey: "birthday")
let birthdayString = birthday as! String
let birthdate = dateFormatter.date(from: birthdayString)
let currentDate = Date()
let calendar: Calendar = Calendar(identifier: .gregorian)
let age = calendar.component(.year, from: birthdate!).distance(to: calendar.component(.year, from: currentDate))
return age
}
func yearsBetween(date1: Date, date2: Date) -> Int {
let calendar = Calendar.current
let components = calendar.dateComponents([Calendar.Component.year], from: date1, to: date2)
return components.year ?? 0
}
// Get Age
let dateString = "01/12/1990"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let date1 = dateFormatter.date(from: dateString)
let date2 = Date()
let age = self.daysBetween(date1:date1!, date2:date2)
Hope it will help you.
You can do a little more Google before ask, also you may find these answers helpful:
How do you create a swift Date object
Calculate age from birth date using NSDateComponents in Swift
func calcAge(birthday:String) -> Int {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
let birthdayDate = dateFormater.date(from: birthday)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
let now: NSDate! = NSDate()
let calcAge = calendar.components(.year, from: birthdayDate!, to: now as Date, options: [])
let age = calcAge.year
return age!
}
usage:
print(calcAge(birthday: "01/12/1990"))

Get just the date (no time) from UIDatePicker

I am trying to get just the date from UIDatePicker:
myDatePicker.datePickerMode = UIDatePicker.Mode.date
var selectedDate=myDatePicker.date
println(selectedDate)
However, this prints more than the date (it prints 2015-04-09 21:45:13 +0000). How do I get just the date part (without the time)? I also set the date picker Mode property to Date.
According to the Apple's documentation datePicker.mode should be date so you can use DateFormatter like so
Swift 4
datePicker.datePickerMode = UIDatePicker.Mode.date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMMM yyyy"
let selectedDate = dateFormatter.string(from: datePicker.date)
print(selectedDate)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yy"
let dateString = dateFormatter.stringFromDate(myDatePicker.date)
You can print dateString, assign it to a label, whatever. The format will be
04/09/15
Swift 3/4, this will print a string of type Mar 08, 2017
datePicker.datePickerMode = .date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"
let selectedDate = dateFormatter.string(from: datePicker.date)
print(selectedDate)
I just want to add my bit in on here after coming across a similar problem. I would follow shades answer for String display of date. Not the from XCode 7 and swift 2 onwards when you use a UIDatePicker set the following to only view dates in the Picker:
#IBOutlet weak var datePicker: UIDatePicker!
datePicker.datePickerMode = .Date
Swift 4.0 version code is here
#IBAction func saveDateAction(_ sender: Any) {
myDatePicker.datePickerMode = UIDatePicker.Mode.date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
let selectedDate = dateFormatter.string(from: myDatePicker.date)
print("selectedDate",selectedDate)
}
Date picker date :
let date = datePicker.date
let dateConverted = Date.init(year: date.GetYear(), month: date.GetMonth(), day: date.GetDay())
//dateConverted result = 2019-02-27 00:00:00 +0000
let predicate = NSPredicate(format: "booking_date == %#", dateConverted as CVarArg)
Use this extensions:
extension Date {
init(year: Int, month: Int, day: Int) {
var dc = DateComponents()
dc.year = year
dc.month = month
dc.day = day
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
if let date = calendar.date(from: dc) {
self.init(timeInterval: 0, since: date)
} else {
fatalError("Date component values were invalid.")
}
}
func GetYear() -> Int {
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
let components = calendar.components([.day , .month , .year], from: self)
return components.year!
}
func GetMonth() -> Int {
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
let components = calendar.components([.day , .month , .year], from: self)
return components.month!
}
func GetDay() -> Int {
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
let components = calendar.components([.day , .month , .year], from: self)
return components.day!
}
}