Modify date format of a string - swift

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

Related

How to format stringDateJson to label? [duplicate]

This question already has answers here:
Convert string to date in Swift
(18 answers)
Closed 1 year ago.
var str = "2021-05-23T06:35:47.409Z"
var formatter = DateFormatter()
formatter.dateFormat = "MMM d yyyy, h:mm:ss a"
let formattedtoDate = formatter.date(from: str)
let formattedtoString = formatter.string(from: formattedtoDate) //Error Cannot force unwrap value of non-optional type 'String'
cell.date_announce.text = formattedtoString
I'm trying to format sting to Date() and format Date to String in order to set value to date_announce label. Can anyone help me please?
If you break down what you are trying to do, there are actually 2 steps that require two different date formatters.
Convert an input date string (e.g. "2021-05-23T06:35:47.409Z") to a Date
Convert the Date to an output string in a different format.
Try this code instead:
var str = "2021-05-23T06:35:47.409Z"
//Set up a DateFormatter for input dates in "Internet" date format"
var inputFormatter = DateFormatter()
inputFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"
//Set up an output date formatter (in the local time zone)
var outputFormatter = DateFormatter()
outputFormatter.dateFormat = "MMM d yyyy, h:mm:ss a"
if let formattedtoDate = inputFormatter.date(from: str) {
let formattedtoString = outputFormatter.string(from: formattedtoDate)
print("'\(str)' = '\(formattedtoString)'")
} else {
print("Can't convert the string \(str) to a Date")
}
Edit:
(As Leo Dabus pointed out in a comment, you usually should not use a fixed dateFormat string in a DateFormatter that generates user-visible date strings. Better to use date and time styles and let the DateFormattter pick a specific format appropriate to the user's locale and language.)

dateformat spelling format swift

I am removing the current time from the current time and trying to find the minute difference. But it says 10/09/2019 13:13 and there is an error in the extraction process (I want to print as 1313) .1313 I can perform the extraction process. How do I print this data the way I want? I want to print dateFormat = "HHmm". In timertext2New.text, dateFormat = "dd / MM / yyyy HH: mm" like this. But I want to save it in HHmm format.
save12 output: 05/09/2019 10:48 but I want it to be "1048" . To perform extraction.
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy HH:mm"
timertext2New.text = formatter.string(from: datePicker.date)
let timehafıza2 = String(self.timertext2New.text!)
let df2 = DateFormatter()
df2.dateFormat = "HHmm"
var str2 = df2.string(from: Date())
str2 = timehafıza2
UserDefaults.standard.setValue(str2, forKey: "timertext2")
override func viewDidLoad() {
super.viewDidLoad()
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HHmm"
let hour = dateFormatter.string(from: date)
var save12 = UserDefaults.standard.integer(forKey: "timertext2")
var fark : Int = (Int(hour)! - Int(save12))
}
Your code is pretty confusing and cannot work
You convert a date from a date picker with format "dd/MM/yyyy HH:mm"
Then you create a string with format "HHmm" from the current date which will be destroyed immediately because
You overwrite this string with the dd/MM/yyyy HH:mm string and save it to UserDefaults
Later you read the value from UserDefaults as integer which returns 0 because the "dd/MM/yyyy HH:mm" format is not representable by an integer.
My suggestion is to save all dates as Date and perform the date math with the dedicated methods of Calendar

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"

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