How to remove Optional(" ") and format date in Swift - ios

I have the following code:
let dateToday = NSDate()
I “pass” it to the Score View Controller via a function:
func saveScore(){
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let gameResult = NSEntityDescription.insertNewObjectForEntityForName("SaveGame", inManagedObjectContext: appDelegate.managedObjectContext) as! SaveGame
gameResult.datePlayed = dateToday
// other data goes here
self.performSegueWithIdentifier(“scoreSegue", sender: self)
}
In the Score View Controller, I display it as:
cell.textLabel?.text = "Date: \(game.datePlayed)
However, I only get this line with the Optional(" ") line.
pls check my screenshot
How do I remove the Optional (" ") and how do I format the date to:
MM/dd/yyyy hh:mm (AM/PM)?

To remove the Optionnal("") indication you can use conditionnal binding like this :
if let date = game.datePlayed {
cell.textLabel?.text = "Date: \(date)"
} else {
//Here display something if no date is available
}
You could also force unwrap your variable with game.datePlayed! but I would recommend against it
To format your date to something readable, use NSDateFormatter like that:
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.LongStyle
formatter.timeStyle = .MediumStyle
let dateString = formatter.stringFromDate(date)
You can change the dateStyle and timeStyle to suit your needs (choice between: .ShortStyle, .MediumStyle, .LongStyle and .FullStyle)
Additionaly you could use a custom date formatter like the following:
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd 'at' HH:mm"
let dateString = formatter.stringFromDate(date)

Related

Convert UTC date to local date swift4

All,
I am trying to convert UTC date to local date . Below is my code. But, even after converting I get both dates in UTC only.
static func getTodayDateInLocalTimeZone() -> Date{
let todaydateInUTC = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
let utcDateString = dateFormatter.string(from: todaydateInUTC)
print("Date::: utcDateString: \(utcDateString)")
// Changing to Current timezone
let timzoneIdentiier = TimeZone.current.identifier
let timezone = TimeZone(identifier: timzoneIdentiier)
let abbrv = timezone?.abbreviation()
let dateFormatter1 = DateFormatter()
dateFormatter1.timeZone = TimeZone(identifier: abbrv!)
dateFormatter1.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
print("Date:::timeZone: \(timzoneIdentiier) == \(String(describing: abbrv))")
let formattedDate1 = dateFormatter1.date(from: utcDateString)
print("Date:::: \(formattedDate1)")
return formattedDate1!
}
Here is what I get when I print
Date::: utcDateString: 2021-01-20T17:39:15+0000
Date:::timeZone: America/New_York == Optional("EST")
Date:::: Optional(2021-01-20 17:39:15 +0000)
Please let me know why is it now changing to the local timezone.
Thanks
First of all, a date does not have a time zone.
So let todaydateInUTC = Date() actually means let todaydate = Date().
The time zone becomes relevant, when you want to present a date to the user.
So instead of creating a new date from a the utcDateString, you just need to create another date string from the same date variable.
let formattedDate1 = dateFormatter1.date(from: utcDateString) becomes let tzDateString = dateFormatter1.string(from: todaydate).
This also means your function should return a string instead of a date.
For example:
func getTodayDateInLocalTimeZone() -> String
{
let now = Date()
// Just for debugging. Not for the result.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
let utcDateString = dateFormatter.string(from: now)
print("Date::: utcDateString: \(utcDateString)")
let tz = TimeZone.current
let dateFormatter1 = DateFormatter()
dateFormatter1.timeZone = tz
dateFormatter1.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
print("Date:::timeZone: \(tz) == \(String(describing: tz.abbreviation()))")
let tzDateString = dateFormatter1.string(from: now)
print("Date:::: \(tzDateString)")
return tzDateString
}
For me it results in:
Date::: utcDateString: 2021-01-20T18:19:44+0000
Date:::timeZone: Europe/Berlin (current) == Optional("CET")
Date:::: 2021-01-20T19:19:44+0100

ISO8601 date from server is not visible in the label

I am getting a date in response from the server which i want to display in the label but when i am displaying it, nil is returned plz help.
my code:
let pulledDate = "2018-04-27T02:05:00+00:00"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
let date = dateFormatter.date(from: pulledDate!) // nil
You can use like this:
You were passing the Wrong Format I guess
Way One
let pulledDate = "2018-04-27T02:05:00+00:00"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let date = dateFormatter.date(from: pulledDate)
print(date!)
The Output
Way Two
let pulledDate = "2018-04-27T02:05:00+00:00"
let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from: pulledDate)
print(date!)
The Output:
Use it the Way you Want.
Hope this help.

Convert NSDate to String in iOS Swift [duplicate]

This question already has answers here:
Convert NSDate to NSString
(19 answers)
Closed 5 years ago.
I am trying to convert a NSDate to a String and then Change Format. But when I pass NSDate to String it is producing whitespace.
let formatter = DateFormatter()
let myString = (String(describing: date))
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
print(yourDate)
you get the detail information from Apple Dateformatter Document.If you want to set the dateformat for your dateString, see this link , the detail dateformat you can get here
for e.g , do like
let formatter = DateFormatter()
// initially set the format based on your datepicker date / server String
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: Date()) // string purpose I add here
// convert your string to date
let yourDate = formatter.date(from: myString)
//then again set the date format whhich type of output you need
formatter.dateFormat = "dd-MMM-yyyy"
// again convert your date to string
let myStringDate = formatter.string(from: yourDate!)
print(myStringDate)
you get the output as
I always use this code while converting Date to String . (Swift 3)
extension Date
{
func toString( dateFormat format : String ) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
and call like this . .
let today = Date()
today.toString(dateFormat: "dd-MM")
DateFormatter has some factory date styles for those too lazy to tinker with formatting strings. If you don't need a custom style, here's another option:
extension Date {
func asString(style: DateFormatter.Style) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = style
return dateFormatter.string(from: self)
}
}
This gives you the following styles:
short, medium, long, full
Example usage:
let myDate = Date()
myDate.asString(style: .full) // Wednesday, January 10, 2018
myDate.asString(style: .long) // January 10, 2018
myDate.asString(style: .medium) // Jan 10, 2018
myDate.asString(style: .short) // 1/10/18
Your updated code.update it.
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date as Date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
print(yourDate!)
Something to keep in mind when creating formatters is to try to reuse the same instance if you can, as formatters are fairly computationally expensive to create. The following is a pattern I frequently use for apps where I can share the same formatter app-wide, adapted from NSHipster.
extension DateFormatter {
static var sharedDateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
// Add your formatter configuration here
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter
}()
}
Usage:
let dateString = DateFormatter.sharedDateFormatter.string(from: Date())
After allocating DateFormatter you need to give the formatted string
then you can convert as string like this way
var date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date)
let yourDate: Date? = formatter.date(from: myString)
formatter.dateFormat = "dd-MMM-yyyy"
let updatedString = formatter.string(from: yourDate!)
print(updatedString)
OutPut
01-Mar-2017
You can use this extension:
extension Date {
func toString(withFormat format: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
let myString = formatter.string(from: self)
let yourDate = formatter.date(from: myString)
formatter.dateFormat = format
return formatter.string(from: yourDate!)
}
}
And use it in your view controller like this (replace <"yyyy"> with your format):
yourString = yourDate.toString(withFormat: "yyyy")

timeIntervalSinceDate returns the wrong value

I have two functions.
The first is writing NSDate() to NSUserDefaults as a string.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"
let dateString = dateFormatter.stringFromDate(NSDate())
NSUserDefaults.standardUserDefaults().setObject(dateString, forKey: "lastDate")
NSUserDefaults.standardUserDefaults().synchronize()
The second one is reading this value, converting it to NSDate and comparing with the current time and date.
let dateString = try NSUserDefaults.standardUserDefaults().stringForKey("lastDate")
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"
if dateString != nil {
let date = try dateFormatter.dateFromString(dateString!)
if date != nil {
let interval = NSDate().timeIntervalSinceDate(date!)
let interval2 = Int(interval)
print(interval2)
}
} else {
//some code here
}
The thing is, it returns not 5 seconds (as it should, for example) but something like 43295 or 44592. I logged dates and strings and they seemed fine. Where did I break things?

How do i get a number data and date data from parse and put it to UILabel?

Currently I want to retrieve createdAt and price from parse database and the datatypes for both are Number and NSDate. After I retrieved it I want to pass to UILabel which is date and price respectively. The problem right now is that whenever I tried to run the simulator, both of the UILabel data don't show up while string data type does show up.
My current code
if let createdAt = object?["createdAt"] as? String {
cell.date.text = createdAt
}
if let priceTitle = object?["price"] as? String {
cell.price.text = priceTitle
}
For Date, use NSDateFormatter.stringFromDate method so your code should be:
if let createdAt = object?["createdAt"] as? NSDate {
let dateFormatter = NSDateFormatter()
var theDateFormat = NSDateFormatterStyle.ShortStyle
dateFormatter.dateStyle = theDateFormat
cell.date.text = dateFormatter.stringFromDate(createdAt)
}
createdAt is a special value in Parse. It is PFObject's property and you access it with dot notation. So this is how you should proceed:
if let object = object as? PFObject {
let date = object.createdAt
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm MMMM dd, yyyy"
let dateStr = dateFormatter.stringFromDate(date!)
cell.date.text = dateStr
}

Resources