Swift date formatting - swift

I'm trying to pull a date string from a button and format is as a date to be store in CoreData.
Here is my code:
let dateStr = setDateBTN.titleLabel?.text
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-YYYY"
let date:NSDate = dateFormatter.dateFromString(dateStr!)!
If I do a println on dateStr I get the following: 03-10-2015. Then if I immediately println on date I get: 2014-12-21 05:00:00 +0000.
Any ideas as to why the actual date is changing when I run it through the date formatter?

NSDateFormatter Class Reference : http://goo.gl/7fp9gl
Date Formatting Guide (Apple) : http://goo.gl/8zRTQl
A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar.
Your code should work, as you expect, like this :
let dateStr = setDateBTN.titleLabel?.text
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date:NSDate = dateFormatter.dateFromString(dateStr!)!

Related

Swift ISO8601DateFormatter TimeZone

I receive a string timestamp from JSON formatted as follows: "2022-10-06T19:10:00.000Z"
I want to convert the string to my local timezone and possibly even reformat the whole thing to something more readable like "Oct 6 2022, 3:30:45 PM". I assume that I need to use both ISO8601DateFormatter() and DateFormatter() to make that happen?
When I run the code below I get "2022-10-07 02:10:00 +0000" which is tomorrow's date so obviously not my timezone.
How do I properly format this date/time stamp to my current timezone? Thanks!
let jsonDateString = "2022-10-06T19:10:00.000Z"
let dateFormatter = ISO8601DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.formatOptions = [.withYear, .withMonth, .withDay, .withTime, .withDashSeparatorInDate, .withColonSeparatorInTime]
let formattedDate = dateFormatter.date(from: jsonDateString)
print(formattedDate!)

Got nil after string to date convertation

I need to convert String simular to "2016-07-10T21:32:20G" to Date.
But for some reason I've got only nil again and again.
I've read an article about date formater. And unfortunately haven't fount an answer there. I found something in the documentation. And documentation tels to read about Unicode Date Format Patterns. And it looks similar to mine.
Probably I missed something =(
My Code example. Unfortunately always get nil.
let lastUpdatedDateString = "2016-07-10 21:32:20"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-mm-dd hh:mm:ss"
let lastUpdated = dateFormatter.date(from:lastUpdatedDateString)
But this code works fine:
let lastUpdatedDateString = "2016-07-10"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-mm-dd"
let lastUpdated = dateFormatter.date(from:lastUpdatedDateString)
I'm testing it in the playground.
In fact I must convert this String("2016-07-10T21:32:20G") to Date.
PS
Anyway, thanks for attention =)
Think it's just the capitalisation in your formatter. Try this ...
let lastUpdatedDateString = "2016-07-10 21:32:20"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let lastUpdated = dateFormatter.date(from:lastUpdatedDateString)
This is what I get with the playground
let lastUpdatedDateString = "2016-07-10T21:32:20"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-ddEEEEEHH:mm:ss"
let lastUpdated = dateFormatter.date(from:lastUpdatedDateString)
print(lastUpdated)
and it prints: Optional(2016-07-10 19:32:20 +0000) (I'm GMT+2)
I don't know what the G stands for so I'm not sure how I can get the last character for the pattern. EEEEE stands for day of the week (1 character)
EDIT: It seems G stand for gregorian calendar
so you can parse the last letter out of the string and add this if it's gregorian calendar (but I suppose this is the default value):
dateFormatter.calendar = Calendar(identifier: .gregorian)
If the letter's a J it's Julian calendar then and you can see this answer to see how to convert gregorian to julian: https://stackoverflow.com/a/12137019/2106940

How to convert a String to NSdate?

I am trying to convert fajerTime to NSDate. When I compile the project the dateValue is nil. Any idea how to fix this issue?
if prayerCommingFromAdan.id == 0 && prayerCommingFromAdan.ringToneId != 0{
// NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name:"NotificationIdentifier", object: nil)
let fajerTime = "\(prayer0.time[0...1]):\(prayer0.time[3...4])" as String
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
dateFormatter.timeZone = NSTimeZone.localTimeZone()
// convert string into date
let dateValue = dateFormatter.dateFromString(fajerTime) as NSDate!
print(dateValue)
var dateComparisionResult:NSComparisonResult = NSDate().compare(dateValue)
if dateComparisionResult == NSComparisonResult.OrderedDescending {
addNotificationAlarm(year, month: month, day: day, hour: prayer0.time[0...1], minutes: prayer0.time[3...4], soundId: prayerCommingFromAdan.ringToneId, notificationBody: "It is al fajr adan")
}
The problem seems be the format of fajerTime. It looks like fajerTime is a time string, e.g. 12:34, whereas the date formatter is configured to accept string containing a month, day and year, e.g. 24-07-2016.
You need to format fajerTime to include the year, month and day, as well as the time. Also configure the date formatter to accept the full date and time.
Assuming prayer0 is an array, you will also need to combine the elements into a string, using joinWithSeparator.
e.g.
let hours = prayer0.time[0...1].joinWithSeparator("")
let minutes = prayer0.time[3...4].joinWithSeparator("")
let fajerTime = "\(month)-\(day)-\(year) \(hours):\(minutes)"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy hh:mm"
dateFormatter.timeZone = NSTimeZone.localTimeZone()
// convert string into date
let dateValue = dateFormatter.dateFromString(fajerTime) as NSDate!
Please follow example (Swift 3):
let dateStr = "2016-01-15 20:10:01 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let myDate = dateFormatter.date(from: dateStr)
Keep in mind:
Date format e.g. "yyyy-MM-dd HH:mm:ss Z" must match the date string pattern
In your case, your date string contains only time, yet, your date
formatter contains only date
When using dateFormatter.date() there is no need to cast it to Date as it returns a Date:
Helpful website for date formats:
http://nsdateformatter.com/

from string to Nsdate Swift

I get date from MySql database in this form:
dd/MM/yyyy HH:mm:ss
for example : 19/09/2015 14:39:18
I want convert this string in NSDate object in Swift , and for this reason I did like this:
var d = "19/09/2015 14:39:18"
var form : NSDateFormatter = NSDateFormatter()
form.dateFormat = "dd/MM/yyyy HH:mm:ss"
print(form.dateFromString(d)!)
but I get by last print this:
2015-09-19 12:39:18 +0000
What's wrong?
You need to tell your NSDateFormatter that the incoming date strings are formatted for the GMT time zone:
var d = "19/09/2015 14:39:18"
var form : NSDateFormatter = NSDateFormatter()
form.timeZone = NSTimeZone(name: "GMT")
form.dateFormat = "dd/MM/yyyy HH:mm:ss"
print(form.dateFromString(d)!)
Prints:
"2015-09-19 14:39:18 +0000"
If you omit manually setting the timeZone property, the NSDateFormatter will inherit the current system time zone, and parse it as if it were a local format time. Then when you're printing the new NSDate object, it's being displayed in GMT, which results in the offset.
Edit: Once you have your NSDate object, you can then use the same formatter to go back to a string representation with the same format:
var d = "19/09/2015 14:39:18"
var form : NSDateFormatter = NSDateFormatter()
form.timeZone = NSTimeZone(name: "GMT")
form.dateFormat = "dd/MM/yyyy HH:mm:ss"
form.stringFromDate(form.dateFromString(d)!) // "19/09/2015 14:39:18"

Modify date format of a string

I'm trying to modify the date format of a string in Swift.
I need to print my date to the french format :
17 mai 2015
I tried this :
var myDate = "2015-05-17 13:00:00"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "d MMMM"
var readableDate = dateFormatter.dateFromString(myDate)
println("Readable date = \(readableDate!)")
I obtain a nil value when I run the program, and I don't understand why.
.dateFromStringcreates an NSDate() from a String. The format of the string has to be set with .dateFormat
You set the format to "d MMMM" but your myDate variable does not conform to that format.
I believe you want to make a String in your "d MMMM" format out of a date.
Take this code as a starting-point:
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "d MMMM"
var readableDate = dateFormatter.stringFromDate(NSDate())
println("Readable date = \(readableDate)")
Check out the Class Reference for NSDate for further assistance