Saving Date in NSUserDefault gives incorrect values - ios

When I print the value that has been stored in NSUserDefaults, I get the following output.
let prefs = NSUserDefaults.standardUserDefaults()
prefs.setObject(NSDate(), forKey: "ST")
print ("Hey \(prefs.objectForKey("ST")) ")
Hey Optional(2016-10-24 08:29:20 +0000)
There's a text Optional( displayed and what I want is to display only the Date time.
In addition, the time given is incorrect. How can i solve this ?

Maybe you can save your date as a formatted String
let formatter: DateFormatter = DateFormatter()
formatter.dateFormat = "yyyy.MM.dd HH:mm:ss ZZZ"
// Save Date...
let hoy: Date = Date()
let formato_hoy = formatter.string(from: hoy)
print(formato_hoy)
// Recover Date...
let future_format: String = "2016.10.24 09:54:22 +0200"
if let future = formatter.date(from: future_format)
{
print(future)
}
The ZZZ value in mask is related to time zone.

Related

How to get only time from date in swift

This question is not asked for the first time, but no solution works for me. I am getting time in String from Api response in the following format "14:45".
I want to compare this time with the current time, for this purpose I need to convert this string in Time formate(swift sports)
I always get nil after conversion
I have tried multiple ways but none of them worked for me and one is given for reference, I don't know what am I missing here
Thanks for any response
func stringToTime(str:String) -> Date{ // 14:45 passed here in str
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
print(str)
//here time string prints
let date = dateFormatter.date(from: (str))
print(date)
//date is nil here, should be 02:45 pm
return date!
}
If the time you get from the API is in 24h format you can do a string comparison
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
let currentTime = formatter.string(from: Date())
let compare = currentTime.compare("14:45")
You might need to set the time zone for the DateFormatter to make sure it uses the same as the API
It seems like you want to transform a time string in one format to another format. Your method signature should look like this:
func changeFormat(str:String) -> String {
Note that you should not output a Date here, because Dates don't have formats. They will always be printed in the same way. What you need to do in this method is 2 things:
parse str to a Date using a DateFormatter, specifying the format HH:mm. You seem to assume that DateFormatter can automatically work this format out. It can't :(
format the Date object you just got using a DateFormatter, specifying the format hh:mm a. This produces a string, not a date.
(You could also consider having the method return a Date (then it would be called parseTime), and do the second step just before you show the date to the screen.)
func changeFormat(str:String) -> String {
let dateFormatter = DateFormatter()
// step 1
dateFormatter.dateFormat = "HH:mm" // input format
let date = dateFormatter.date(from: str)!
// step 2
dateFormatter.dateFormat = "hh:mm a" // output format
let string = dateFormatter.string(from: date)
return string
}

Formatting JSON date to Swift date doesn't work

I'm trying to format this date: 2018-01-10T11:57:21.153 to Swift Date object like this:
let dateSentString = jsonDict["date"] as! String
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from: dateSentString)!
For some reason, the app crashes on the last line.
What am I doing wrong? Thanks!
change the milli seconds format use 'SSS' specifier (with number of S's equal to number of digits of milliseconds ). for more information you get here
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
from
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
Full code
let dateSentString = "2018-01-10T11:57:21.153"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
let date = dateFormatter.date(from: dateSentString)!
print(date)
You have to first set formatter for date you are getting from JSON and then another formatter for the date you want.
First convert string fro JSON to a date variable by setting same format coming in JSON object .
Then you have to re-format that date variable into format you want.
I can write code if you want but it is better to try yourself.
Happy Coding

dateFromString() returning wrong date swift 3.0

i am passing "01/12/2017" in the fromDate.text(textfield), but receiving unexpected output.
let formatter = DateFormatter.init()
formatter.dateFormat = "dd/mm/yyyy"
startDate = formatter.date(from: fromDate.text!)
print("startDate = \(startDate)")
output is : 31/12/2016
The format of date should be dd/MM/yyyy not dd/mm/yyyy. The mm indicates the minutes and MM indicates the month.
And also add the below line in your code
formatter.timeZone = TimeZone(abbreviation: "GMT+0:00")
This line of code set time zone. If you not, then you get 30/11/2017 in output.
The reason behind this is when string date not contain time then formatter assume that it is midnight and you also not given the timezone so it will take current timezone.
It has to be dd/MM/yyyy dateformat. MM in capital.
func convertToString(of dateTo: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy" //Your New Date format as per requirement change it own
let newDate: String = dateFormatter.string(from: dateTo) //pass Date here
print(newDate) //New formatted Date string
return newDate
}

Converting UTC to EST in Swift

I have a string of text in my application that conveys a time and the date, such as let time = "2017-07-09T09:17:08+00:00". I want to take this string, which is in UTC, and convert it to a string that presents the time in EST. For my example, the resulting string would be 2017-07-09T05:17:08+00:00. How can this be done?
I've tried using
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.timeZone = TimeZone.current
let date = dateFormatter.date(from:time!)!
but printing the date gives me the same time in UTC.
All you need to do is to use a DateFormatter to convert your Date object into a String. By default, the date will be formatted to local time.
// First, get a Date from the String
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:time!)!
// Now, get a new string from the Date in the proper format for the user's locale
dateFormatter.dateFormat = nil
dateFormatter.dateStyle = .long // set as desired
dateFormatter.timeStyle = .medium // set as desired
let local = dateFormatter.string(from: date)
Note that there is no need to set any timezone for either set of code in this case.

Replacing current date with String containing time in Swift

I'm making an app where i get time from Parse as String e.g. "13:24" i need to prepare it to save in CoreData as Date, but replacing the time with this String to use it later in fireDate notification. What's the best approach to do this ? I should get the currentDate(), change it into string and somehow replace it with my timeString from Parse ?
You can use this snippet to get todays date + custom time:
let time = "12:34"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd HH:mm"
var todayDateString = dateFormatter.stringFromDate(NSDate())
todayDateString.replaceRange(Range<String.Index>(start: todayDateString.endIndex.advancedBy(-5), end: todayDateString.endIndex), with: time)
let newDate = dateFormatter.dateFromString(todayDateString)

Resources