from string to Nsdate Swift - 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"

Related

Converting string to date returning the day before

I have a date in a string with this format "2017-03-14" (yyyy-MM-dd) and i am trying to convert it into a string with this format "Tuesday, March 14, 2017".
This is my code:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: "2017-03-14")
Now if i print the value of "date", i get this:
2017-03-13 22:00:00 +0000
This is just the day before. Why is that ?
EDIT:
I need to compare date before formatting it.
var newDateString : String = ""
let date2 = Date()
let comp = date2.compare(date!)
if comp.rawValue == 0 {
newDateString = "TONIGHT"
} else {
dateFormatter.dateFormat = "EEEE, MMMM d, yyyy"
newDateString = dateFormatter.string(from: date!)
}
Thanks
The desired Format should be:
EEEE, MMMM dd, yyyy
All you have to do is to add after your code the following code snippet:
dateFormatter.dateFormat = "EEEE, MMMM dd, yyyy"
let string = dateFormatter.string(from: date!) // "Tuesday, March 14, 2017"
Remark:
I'd like to suggest to do optional binding for declaring the date, as follows:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
if let date = dateFormatter.date(from: "2017-03-14") {
dateFormatter.dateFormat = "EEEE, MMMM dd, yyyy"
let string = dateFormatter.string(from: date) // "Tuesday, March 14, 2017"
}
Your confusion is based on a misunderstanding of what Time and Date are. Evidently, you are currently located in a time zone that is 2 hours ahead of UTC (Coordinated Universal Time), previously known as Greenwich Mean Time (GMT).
When you ask the OS for a Date object converted from "2017-03-14" you get a date/time reference of Midnight the morning of 2017-03-14 in your time zone which is, correctly, 10:00 pm (22:00) then night before in UTC.
When you ask the OS for a Date object for now with Date() you get a date/time reference of now in your time zone, which will be two hours earlier in UTC.
To accurately evaluate your date string to say "is now earlier than 'tonight of 2017-03-14'" you will probably want to convert from "2017-03-14 23:59" (or 11:59 pm, or perhaps prior to the start of tonight's event of 8:00 pm, etc).
This will do your original comparison, but would work better as a function (although I'm not sure how you want to use it)...
var newDateString : String = ""
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
// set tonightDate to 1 minute before midnight, tonight, in local time
if let tonightDate = dateFormatter.date(from: "2017-03-14 23:59") {
// set nowDate to current local time
let nowDate = Date()
let comp = nowDate.compare(tonightDate)
if comp.rawValue <= 0 {
newDateString = "TONIGHT"
} else {
dateFormatter.dateFormat = "EEEE, MMMM d, yyyy"
newDateString = dateFormatter.string(from: tonightDate)
}
}
print(newDateString)
It is calculated time based on UTC so you are getting day before.You can get proper format using below code:
func chageDateFormat(date:String) -> String{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
guard let date = dateFormatter.dateFromString(date) else {
assert(false, "No date from string")
return ""
}
print(date)
dateFormatter.dateFormat = "EEEE, dd MMMM, yyyy"
let result = dateFormatter.stringFromDate(date)
return result
}
let resultFormateDate = chageDateFormat("2017-03-14")
For comparison you also need to convert Date() to proper format.Both date must be in same format.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = NSDate()
let strdate = dateFormatter.stringFromDate(date)
let resultFormateDate2 = chageDateFormat(strdate)
Now you can compare two strings
if resultFormateDate == resultFormateDate2{
print("True")
}

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/

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

dateFromString returns nil every time format possibly wrong?

I am trying to use date from string method like below:
var dateNow = self.tags![indexPath.row].date!
let timeZone = NSTimeZone(name: "UTC")
let df = NSDateFormatter()
df.locale = NSLocale.currentLocale()
df.timeZone = timeZone
df.dateFormat = "yyyy-MM-ddThh:mm"
let date: NSDate = df.dateFromString(dateNow)! //this is nil and throws an unwrapping error
The date is formatted like this
dateNow String "2015-04-19T17:00:42.205Z"
Im guessing maybe that is formatted wrong but I have no idea how to write the df.dateFormat
you just have to format it as follow:
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
Yet another way to get nil is if you use hh and your hours are on the 24 hr clock and > 12, in that case, you need HH (or H, for zero-padded).
That is:
Format: yyyy-MM-DD hh:mm:ss, string: "2016-03-01 13:42:17" will return nil .
Format: yyyy-MM-DD HH:mm:ss, string: "2016-03-01 13:42:17" will return the date you expect.

Swift date formatting

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!)!