Date picker shows a different date (1 day behined) from when picked - ios

I have a UIDatePicker that is connected to a UILabel. I want the user to pick a birthday that is more than 18 years ago (age restriction). So I have this line to set the maximumDate value:
datePicker.maximumDate = NSCalendar.currentCalendar().dateByAddingUnit(.Year, value: -18, toDate: NSDate(), options: [])
This line however causes the picker to show a 1 day behind the selected date. for example if I choose September 27, 1956 on the picker the label shows September 26, 1956 I believe it has to do with NSDate() using a different timezone one that is behind my local timezone.
switch dequeueFrom[indexPath.row] {
case .Birthday:
if let pickedBday = pickedBday,
let bday = NSDate.dateFromISOString(pickedBday) {
(cell as! RegisterTextFieldCell).content(bday.longFormattedString())
}
// dateFromISOSString is declared in an extension.swift
class func dateFromComponents(components: NSDateComponents) -> NSDate? {
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
return calendar?.dateFromComponents(components)
}
class func dateFromString(string: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss-SSS"
if let stringDate = dateFormatter.dateFromString(string) {
return stringDate
} else {
return nil
}
}
func ISOStringFromDate() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
return dateFormatter.stringFromDate(self).stringByAppendingString("Z")
}
class func dateFromISOString(string: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let stringDate = dateFormatter.dateFromString(string) {
return stringDate
} else {
return nil
}
}
Any help with how I can make NSDate() be my local timezone so this one day behind issue can go away? Any help is greatly appreciated :)

The problem is in your method ISOStringFromDate because you are getting the local time and manually adding the Z (Z means UTC) to the string. Try like this when creating your iso8601:
extension NSDate {
var iso8601: String {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
return dateFormatter.stringFromDate(self)
}
}
and your code should be:
pickedDate.iso8601 // to get your date iso8601 string

Related

Date time conversion in swift 5

I want to convert 2021-04-23T07:43:52.532656+00:00 to 04 April, 2021 7:43 Am
I am getting the day month and year correct but I have problems when formatting the time can somebody help me
My problem when converting time - I want the same time but when formatting it goes to the current time zone
func dateFormating(date : String) -> Date{
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//yyyy-MM-dd'T'HH:mm:ssZ
// var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "UTC" }
// dateFormatter.locale = Locale.init(identifier: localTimeZoneAbbreviation)
// dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone.local
return dateFormatter.date(from: date) ?? Date()
}
func dateConverter(date : Date) -> String {
print("date in here 1 = \(date)")
let dateFormatterNormal = DateFormatter()
dateFormatterNormal.dateFormat = date.dateFormatWithSuffix()
// var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "UTC" }
// dateFormatterNormal.locale = Locale.init(identifier: localTimeZoneAbbreviation)
// dateFormatterNormal.locale = Locale(identifier: "en_US_POSIX")
// dateFormatterNormal.timeZone = TimeZone.current
let endDate = dateFormatterNormal.string(from: date )
print("endinf date == \(endDate)")
return endDate
}
func dateFormatWithSuffix() -> String {
return " MMM , yyyy h:mm a"
}

NSDate Extension not working

This is a piece of code that was working in earlier version of swift. It is now giving an error (Cannot convert value of type 'NSDate' to type 'NSDate.Date' in coercion)
extension NSDate {
struct Date {
static let formatterISO8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.ISO8601)! as Calendar
formatter.locale = NSLocale.current
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) as TimeZone!
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXX"
return formatter
}()
}
var formattedISO8601: String { return Date.formatterISO8601.string(from: self as Date) }
}
Issue is that in Swift 3 there is already a structure define with named Date.
So what you can do is change your struct name to MyDate or something else and you all set to go.
Also it is better if you use new Date, Calendar and TimeZone instead of NSDate, NSCalendar and NSTimeZone.
Or make extension of Date like this way.
extension Date {
static let formatterISO8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale.current
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXX"
return formatter
}()
var formattedISO8601: String { return Date.formatterISO8601.string(from: self) }
}
Extensions for both NSDate and Date.
extension Date {
static let formatterISO8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.ISO8601)! as Calendar
formatter.locale = NSLocale.current
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) as TimeZone!
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXX"
return formatter
}()
func formattedISO8601() -> String {
return Date.formatterISO8601.string(from: self)
}
}
extension NSDate {
func formattedISO8601() -> String {
return Date.formatterISO8601.string(from: self as Date)
}
}
And use it like this ...
// NSDate
let nsdate = NSDate.init()
let formattedDate = nsdate.formattedISO8601()
// Date
let date = Date.init()
let formattedNsDate = date.formattedISO8601()
try this
extension Date {
static let formatterISO8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.ISO8601)! as Calendar
formatter.locale = NSLocale.current
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) as TimeZone!
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXX"
return formatter
}()
var formattedISO8601: String { return Date.formatterISO8601.string(from: self)
}
}

Swift 3 changing date format

I want to get my Date in DD.MM.YYYY HH:mm:ss as a String.
I use the following extension:
extension Date {
var localTime: String {
return description(with: Locale.current)
}
}
and the following code when my datePicker changes:
#IBAction func datePickerChanged(_ sender: UIDatePicker) {
dateLabel.text = datePicker.date.localTime
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy hh:mm"
let TestDateTime = formatter.date(from: datePicker.date.localTime)
}
What am I doing wrong?
Your code is completely wrong. Just do the following:
#IBAction func datePickerChanged(_ sender: UIDatePicker) {
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy HH:mm"
dateLabel.text = formatter.string(from: sender.date)
}
This will convert the date picker's chosen date to a string in the format dd.MM.yyyy HH:mm in local time.
Never use the description method to convert any object to a user presented value.
Just used the function in your code(swift 4.2).
public func convertDateFormatter(date: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"//this your string date format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
dateFormatter.locale = Locale(identifier: "your_loc_id")
let convertedDate = dateFormatter.date(from: date)
guard dateFormatter.date(from: date) != nil else {
assert(false, "no date from string")
return ""
}
dateFormatter.dateFormat = "HH:mm a"///this is what you want to convert format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let timeStamp = dateFormatter.string(from: convertedDate!)
print(timeStamp)
return timeStamp
}
Thanks

Convert string to DATE type in swift 3 [duplicate]

This question already has answers here:
Dateformatter to get Date From String
(4 answers)
Closed 4 years ago.
I have this structure:
struct message {
var id: String = "0"
var text: String = ""
var date: Date!
var status: String = ""
}
I have to load this structure from dbase, that it export in String format also date.
So I write this code to convert String to Date type:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone!
let dataDate = dateFormatter.date(from: elemMessage["date"] as! String)!
And I load it in structure:
message(id: elemMessage["id"] as! String, text: elemMessage["text"] as! String, date: dataDate as! Date, status: elemMessage["status"] as! String)
But I have this warning: "Cast from Date to unrelated type Date always fails"
So if I run app it will fails.
How Can I fix this, the date var in structure have to be Date type.
Thank you.
You can convert String Date into Date/NSDate like below code: -
Swift 3.2 & Swift 4.2
String to Date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy" //Your date format
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00") //Current time zone
//according to date format your date string
guard let date = dateFormatter.date(from: "01-01-2017") else {
fatalError()
}
print(date) //Convert String to Date
Date to String
dateFormatter.dateFormat = "MMM d, yyyy" //Your New Date format as per requirement change it own
let newDate = dateFormatter.string(from: date) //pass Date here
print(newDate) //New formatted Date string
Output: -
2017-01-11 00:07:00 +0000
Jan 11, 2017
Swift 4 ISO
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone.autoupdatingCurrent
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
func getDateFromString(dateStr: String) -> (date: Date?,conversion: Bool)
{
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
let dateComponentArray = dateStr.components(separatedBy: "/")
if dateComponentArray.count == 3 {
var components = DateComponents()
components.year = Int(dateComponentArray[2])
components.month = Int(dateComponentArray[1])
components.day = Int(dateComponentArray[0])
components.timeZone = TimeZone(abbreviation: "GMT+0:00")
guard let date = calendar.date(from: components) else {
return (nil , false)
}
return (date,true)
} else {
return (nil,false)
}
}
//Input: "23/02/2017"
//Output: (2017-02-23 18:30:00 +0000, true)

Swift - iOS - Dates and times in different format

I am working for an application written in swift and i want to manipulate dates and times
let timestamp = NSDateFormatter.localizedStringFromDate(
NSDate(),
dateStyle: .ShortStyle,
timeStyle: .ShortStyle
)
returns
2/12/15, 11:27 PM
if I want date and time in a different format, for example the date in a European format like dd/mm/yy and the hours in the 24h format without AM and PM. Is there some function that i can use or i have to use N Strings to reorder the various elements?
func convertDateFormater(date: String) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
guard let date = dateFormatter.dateFromString(date) else {
assert(false, "no date from string")
return ""
}
dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let timeStamp = dateFormatter.stringFromDate(date)
return timeStamp
}
Edit for Swift 4
func convertDateFormatter(date: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"//this your string date format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
dateFormatter.locale = Locale(identifier: "your_loc_id")
let convertedDate = dateFormatter.date(from: date)
guard dateFormatter.date(from: date) != nil else {
assert(false, "no date from string")
return ""
}
dateFormatter.dateFormat = "yyyy MMM HH:mm EEEE"///this is what you want to convert format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let timeStamp = dateFormatter.string(from: convertedDate!)
return timeStamp
}
As already mentioned you have to use DateFormatter to format your Date objects. The easiest way to do it is creating a read-only computed property Date extension.
Read-Only Computed Properties
A computed property with a getter but no setter is known as a
read-only computed property. A read-only computed property always
returns a value, and can be accessed through dot syntax, but cannot be
set to a different value.
Note:
You must declare computed properties—including read-only computed
properties—as variable properties with the var keyword, because their
value is not fixed. The let keyword is only used for constant
properties, to indicate that their values cannot be changed once they
are set as part of instance initialization.
You can simplify the declaration of a read-only computed property by
removing the get keyword and its braces:
extension Formatter {
static let date = DateFormatter()
}
extension Date {
var europeanFormattedEn_US : String {
Formatter.date.calendar = Calendar(identifier: .iso8601)
Formatter.date.locale = Locale(identifier: "en_US_POSIX")
Formatter.date.timeZone = .current
Formatter.date.dateFormat = "dd/M/yyyy, H:mm"
return Formatter.date.string(from: self)
}
}
To convert it back you can create another read-only computed property but as a string extension:
extension String {
var date: Date? {
return Formatter.date.date(from: self)
}
func dateFormatted(with dateFormat: String = "dd/M/yyyy, H:mm", calendar: Calendar = Calendar(identifier: .iso8601), defaultDate: Date? = nil, locale: Locale = Locale(identifier: "en_US_POSIX"), timeZone: TimeZone = .current) -> Date? {
Formatter.date.calendar = calendar
Formatter.date.defaultDate = defaultDate ?? calendar.date(bySettingHour: 12, minute: 0, second: 0, of: Date())
Formatter.date.locale = locale
Formatter.date.timeZone = timeZone
Formatter.date.dateFormat = dateFormat
return Formatter.date.date(from: self)
}
}
Usage:
let dateFormatted = Date().europeanFormattedEn_US //"29/9/2018, 16:16"
if let date = dateFormatted.date {
print(date.description(with:.current)) // Saturday, September 29, 2018 at 4:16:00 PM Brasilia Standard Time\n"\
date.europeanFormattedEn_US // "29/9/2018, 16:27"
}
let dateString = "14/7/2016"
if let date = dateString.toDateFormatted(with: "dd/M/yyyy") {
print(date.description(with: .current))
// Thursday, July 14, 2016 at 12:00:00 PM Brasilia Standard Time\n"
}
As Zaph stated, you need to follow the documentation. Admittedly it may not be the most straightforward when compared to other class references. The short answer is, you use Date Field Symbol Table to figure out what format you want. Once you do:
let dateFormatter = NSDateFormatter()
//the "M/d/yy, H:mm" is put together from the Symbol Table
dateFormatter.dateFormat = "M/d/yy, H:mm"
dateFormatter.stringFromDate(NSDate())
You'll also need to be able to use the table if you need to convert a date that is a string into an NSDate.
let dateAsString = "02/12/15, 16:48"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "M/d/yyyy, H:mm"
let date = dateFormatter.dateFromString(dateAsString)
Current date time to formated string:
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy hh:mm:ss a"
let convertedDate: String = dateFormatter.string(from: currentDate) //08/10/2016 01:42:22 AM
More Date Time Formats
You have already found NSDateFormatter, just read the documentation on it.
NSDateFormatter Class Reference
For format character definitions
See: ICU Formatting Dates and Times
Also: Date Field SymbolTable..
If you want to use protocol oriented programming (Swift 3)
1) Create a Dateable protocol
protocol Dateable {
func userFriendlyFullDate() -> String
func userFriendlyHours() -> String
}
2) Extend Date class and implement the Dateable protocol
extension Date: Dateable {
var formatter: DateFormatter { return DateFormatter() }
/** Return a user friendly hour */
func userFriendlyFullDate() -> String {
// Customize a date formatter
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
formatter.timeZone = TimeZone(abbreviation: "UTC")
return formatter.string(from: self)
}
/** Return a user friendly hour */
func userFriendlyHours() -> String {
// Customize a date formatter
formatter.dateFormat = "HH:mm"
formatter.timeZone = TimeZone(abbreviation: "UTC")
return formatter.string(from: self)
}
// You can add many cases you need like string to date formatter
}
3) Use it
let currentDate: Date = Date()
let stringDate: String = currentDate.userFriendlyHours()
// Print 15:16
I used the a similar approach as #iod07, but as an extension.
Also, I added some explanations in the comments to understand how it works.
Basically, just add this at the top or bottom of your view controller.
extension NSString {
class func convertFormatOfDate(date: String, originalFormat: String, destinationFormat: String) -> String! {
// Orginal format :
let dateOriginalFormat = NSDateFormatter()
dateOriginalFormat.dateFormat = originalFormat // in the example it'll take "yy MM dd" (from our call)
// Destination format :
let dateDestinationFormat = NSDateFormatter()
dateDestinationFormat.dateFormat = destinationFormat // in the example it'll take "EEEE dd MMMM yyyy" (from our call)
// Convert current String Date to NSDate
let dateFromString = dateOriginalFormat.dateFromString(date)
// Convert new NSDate created above to String with the good format
let dateFormated = dateDestinationFormat.stringFromDate(dateFromString!)
return dateFormated
}
}
Example
Let's say you want to convert "16 05 05" to "Thursday 05 May 2016" and your date is declared as follow let date = "16 06 05"
Then simply call call it with :
let newDate = NSString.convertFormatOfDate(date, originalFormat: "yy MM dd", destinationFormat: "EEEE dd MMMM yyyy")
Hope it helps !
Here is a solution that works with Xcode 10.1 (FEB 23 2019) :
func getCurrentDateTime() {
let now = Date()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "fr_FR")
formatter.dateFormat = "EEEE dd MMMM YYYY"
labelDate.text = formatter.string(from: now)
labelDate.font = UIFont(name: "HelveticaNeue-Bold", size: 12)
labelDate.textColor = UIColor.lightGray
let text = formatter.string(from: now)
labelDate.text = text.uppercased()
}
The "Accueil" Label is not connected to the code.
iOS 8+
It is cumbersome and difficult to specify locale explicitly. You never know where your app will be used. So I think, it is better to set locale to Calender.current.locale and use DateFormatter's
setLocalizedDateFormatFromTemplate method.
setLocalizedDateFormatFromTemplate(_:)
Sets the date format from a template using the specified locale for the receiver. - developer.apple.com
extension Date {
func convertToLocaleDate(template: String) -> String {
let dateFormatter = DateFormatter()
let calender = Calendar.current
dateFormatter.timeZone = calender.timeZone
dateFormatter.locale = calender.locale
dateFormatter.setLocalizedDateFormatFromTemplate(template)
return dateFormatter.string(from: self)
}
}
Date().convertToLocaleDate(template: "dd MMMM YYYY")
Swift 3:
//This gives month as three letters (Jun, Dec, etc)
let justMonth = DateFormatter()
justMonth.dateFormat = "MMM"
myFirstLabel.text = justMonth.string(from: myDate)
//This gives the day of month, with no preceding 0s (6,14,29)
let justDay = DateFormatter()
justDay.dateFormat = "d"
mySecondLabel.text = justDay.string(from: myDate)
//This gives year as two digits, preceded by an apostrophe ('09, '16, etc)
let justYear = DateFormatter()
justYear.dateFormat = "yy"
myThirdLabel.text = "'\(justYear.string(from: lastCompDate))"
For more formats, check out this link to a codingExplorer table with all the available formats. Each date component has several options, for example:
Year:
"y" - 2016 (early dates like year 1 would be: "1")
"yy" - 16 (year 1: "01"
"yyy" - 2016 (year 1: "001")
"yyyy" - 2016 (year 1: "0001")
Pretty much every component has 2-4 options, using the first letter to express the format (day is "d", hour is "h", etc). However, month is a capital "M", because the lower case "m" is reserved for minute. There are some other exceptions though, so check out the link!
let usDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-US"))
//usDateFormat now contains an optional string "MM/dd/yyyy"
let gbDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-GB"))
//gbDateFormat now contains an optional string "dd/MM/yyyy"
let geDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "de-DE"))
//geDateFormat now contains an optional string "dd.MM.yyyy"
You can use it in following way to get the current format from device:
let currentDateFormat = DateFormatter.dateFormat(fromTemplate: "MMddyyyy", options: 0, locale: Locale.current)
Added some formats in one place. Hope someone get help.
Xcode 12 - Swift 5.3
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
var dateFromStr = dateFormatter.date(from: "12:16:45")!
dateFormatter.dateFormat = "hh:mm:ss a 'on' MMMM dd, yyyy"
//Output: 12:16:45 PM on January 01, 2000
dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
//Output: Sat, 1 Jan 2000 12:16:45 +0600
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
//Output: 2000-01-01T12:16:45+0600
dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
//Output: Saturday, Jan 1, 2000
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
//Output: 01-01-2000 12:16
dateFormatter.dateFormat = "MMM d, h:mm a"
//Output: Jan 1, 12:16 PM
dateFormatter.dateFormat = "HH:mm:ss.SSS"
//Output: 12:16:45.000
dateFormatter.dateFormat = "MMM d, yyyy"
//Output: Jan 1, 2000
dateFormatter.dateFormat = "MM/dd/yyyy"
//Output: 01/01/2000
dateFormatter.dateFormat = "hh:mm:ss a"
//Output: 12:16:45 PM
dateFormatter.dateFormat = "MMMM yyyy"
//Output: January 2000
dateFormatter.dateFormat = "dd.MM.yy"
//Output: 01.01.00
//Output: Customisable AP/PM symbols
dateFormatter.amSymbol = "am"
dateFormatter.pmSymbol = "Pm"
dateFormatter.dateFormat = "a"
//Output: Pm
// Usage
var timeFromDate = dateFormatter.string(from: dateFromStr)
print(timeFromDate)
let dateString = "1970-01-01T13:30:00.000Z"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let date = formatter.date(from: String(dateString.dropLast(5)))!
formatter.dateFormat = "hh.mma"
print(formatter.string(from: date))
if You notice I have set .dateFormat = "hh.mma"by this you will get time only.
Result:01.30PM
extension String {
func convertDatetring_TopreferredFormat(currentFormat: String, toFormat : String) -> String {
let dateFormator = DateFormatter()
dateFormator.dateFormat = currentFormat
let resultDate = dateFormator.date(from: self)
dateFormator.dateFormat = toFormat
return dateFormator.string(from: resultDate!)
}
}
Call from your view controller file as below.
"your_date_string".convertDatetring_TopreferredFormat(currentFormat: "yyyy-MM-dd HH:mm:ss.s", toFormat: "dd-MMM-yyyy h:mm a")
This is possibly an old thread but I was working on datetimes recently and was stuck with similar issue so I ended up creating a utility of mine which looks like this,
This utility would take a string date and would return an optional date object
func toDate(dateFormat: DateFormatType) -> Date? {
let formatter = DateFormatter()
formatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?
formatter.dateFormat = dateFormat.rawValue
let temp = formatter.date(from: self)
return formatter.date(from: self)
}
the DateFormatType enum looks like this
enum DateFormatType : String {
case type1 = "yyyy-MM-dd - HH:mm:ss"
case type2 = "dd/MM/yyyy"
case type3 = "yyyy/MM/dd"
}
One important thing I would like to mention here is the line
formatter.timeZone = NSTimeZone(name: "UTC") as TimeZone?
it's very important that you add this line because without this the DateFormatter would use it's default conversions to convert the date and you might end up seeing different dates if you are working with a remote team and get all sorts of issues with data depending on dates.
Hope this helps
Time Picker In swift
class ViewController: UIViewController {
//timePicker
#IBOutlet weak var lblTime: UILabel!
#IBOutlet weak var timePicker: UIDatePicker!
#IBOutlet weak var cancelTime_Btn: UIBarButtonItem!
#IBOutlet weak var donetime_Btn: UIBarButtonItem!
#IBOutlet weak var toolBar: UIToolbar!
//Date picker
// #IBOutlet weak var datePicker: UIDatePicker!
override func viewDidLoad() {
super.viewDidLoad()
ishidden(bool: true)
let dateFormatter2 = DateFormatter()
dateFormatter2.dateFormat = "HH:mm a" //"hh:mm a"
lblTime.text = dateFormatter2.string(from: timePicker.date)
}
#IBAction func selectTime_Action(_ sender: Any) {
timePicker.datePickerMode = .time
ishidden(bool: false)
}
#IBAction func timeCancel_Action(_ sender: Any) {
ishidden(bool: true)
}
#IBAction func timeDoneBtn(_ sender: Any) {
let dateFormatter1 = DateFormatter()
dateFormatter1.dateFormat = "HH:mm a"//"hh:mm"
let str = dateFormatter1.string(from: timePicker.date)
lblTime.text = str
ishidden(bool: true)
}
func ishidden(bool:Bool){
timePicker.isHidden = bool
toolBar.isHidden = bool
}
}
new Date(year,month,day,0,0,0,0) is local time (as input)
new Date(year,month,day) is UTC
I was using a function to attain YYYY-MM-DD format to be compatible on iOS web, but that is also UTC when used in comparisons (not chained by getFullYear or similar) I've found it is best to use only the above with strong (hours,minutes,seconds,milliseconds) building a calendar, calculating with a Date objects and local references
export const zeroPad = (num) => {
var res = "0";
if (String(num).length === 1) {
res = `0${num}`;
} else {
res = num;
}
return res;
};

Resources