Swift - Get next date - ios

I am trying to write a function that takes a string (in the format "dd MM yyyy") and returns the day after the one given as a parameter.
For example:
let nextDay = getNextDay("31 12 2016")
print(nextDay)
Would print:
01 01 2017
Can someone show me how to do this? Thanks

Here is the code snippet that may help you.
//Call method like this
convertNextDate(dateString: "31 12 2016")
// Method is here
func convertNextDate(dateString : String){
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MM yyyy"
let myDate = dateFormatter.date(from: dateString)!
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: myDate)
let somedateString = dateFormatter.string(from: tomorrow!)
print("your next Date is \(somedateString)")
}
Another way is to create extension and here it is.
extension String {
func convertToNextDate(dateFormat: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
let myDate = dateFormatter.date(from: self)!
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: myDate)
return dateFormatter.string(from: tomorrow!)
}
}
Usage
print("31 12 2016".convertToNextDate(dateFormat: "dd MM yyyy"))
Note: You can use use your desired date-format just make sure it is appropriate.

class DateHelper
{
lazy var formatter:DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "dd MM yyyy"
return formatter
}()
lazy var dateComponents:DateComponents = {
var dateComp = DateComponents()
dateComp.day = 1
return dateComp
}()
func getNext(dateString:String) -> String?
{
if let date = self.formatter.date(from: dateString),
let nextDate = Calendar.current.date(byAdding: self.dateComponents, to: date)
{
return self.formatter.string(from: nextDate)
}
return nil
}
}
DateHelper().getNext(dateString: "31 12 2016")

Related

Get month and date separately from date string

I have got a date in this format..
2019-12-16 18:30:00 +0000
This is the code I have for that..
var utcTime = "\(dic["dueDate"]!)"
self.dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
self.dateFormatter.locale = Locale(identifier: "en_US")
let date = self.dateFormatter.date(from:utcTime)!
print(date)
I wanted to extract month and date from this string. i.e. from the above date string, I want 'December' & '16' separately.
There are several ways to get the expected result, as an option you can use this code with Calendar:
let utcTime = "2020-01-17T22:01:00"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.locale = Locale(identifier: "en_US")
if let date = dateFormatter.date(from:utcTime) {
let monthInt = Calendar.current.component(.month, from: date)
let dayInt = Calendar.current.component(.day, from: date)
let monthStr = Calendar.current.monthSymbols[monthInt-1]
print(monthStr, dayInt)
}
Welcome to stack overflow.
You can try this :
let calendar = Calendar.current
calendar.component(.year, from: date)
calendar.component(.month, from: date)
calendar.component(.day, from: date)
Hope it helps...
Welcome to stack overflow. Please try this.
func getMonthAndDate(dateString: String) ->(month:String , day:String) {
guard let date = Date.getMonthAndDate(from: dateString, with: "yyyy-MM-dd'T'HH:mm:ss") else {
return ("","")
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM"
let month = dateFormatter.string(from: date)
dateFormatter.dateFormat = "dd"
let day = dateFormatter.string(from: date)
return (month,day)
}
extension Date {
static func getMonthAndDate(from str: String, with formatter: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current//(abbreviation: "GMT") //Set timezone that you want
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = formatter //Specify your format that you want
return dateFormatter.date(from: str)
}
}
Swift 5
Here is the extension you need It returns tuple having Month and date as you wanted to have
extension Date {
func getMonthAndDate() ->(month:String , day:String) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM"
let month = dateFormatter.string(from: self)
dateFormatter.dateFormat = "dd"
let day = dateFormatter.string(from: self)
return (month,day)
}
}
I give you example of month u can get date and month value separately ,
visit link for your format http://userguide.icu-project.org/formatparse/datetime
extension Date {
var month: String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM"
return dateFormatter.string(from: self)
}
}
you can use it in this way:
let date = Date()
let monthString = date.month
try same thing for date, I hope it will work for you... :)
this is an example from your code. I have stored month and day in separate string to show you. You can change according to your requirements.
var utcTime = "2019-12-16 18:30:00 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"
dateFormatter.locale = Locale(identifier: "en_US")
let date = dateFormatter.date(from:utcTime)!
print(date) //2019-12-16 18:30:00 +0000
dateFormatter.dateFormat = "MMMM"
let strMonth = dateFormatter.string(from: date)
print(strMonth) //December
dateFormatter.dateFormat = "dd"
let strDay = dateFormatter.string(from: date)
print(strDay) //16
Also you can use Calendar object to get date, month (gives you in digit) and year.
var utcTime = "2019-12-16 18:30:00 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"
dateFormatter.locale = Locale(identifier: "en_US")
let date = dateFormatter.date(from:utcTime)!
let calendarDate = Calendar.current.dateComponents([.day, .year, .month], from: date)
let day = calendarDate.day
print(day) //16
let month = calendarDate.month
print(month) //12
let year = calendarDate.year
print(year) //2019
You can get the day, month and year as follows
let yourDate = Calendar.current.dateComponents([.day, .year, .month], from: Date())
if let day = yourDate.day, let month = yourDate.month, let year = yourDate.year {
let monthName = Calendar.current.monthSymbols[month - 1]
// your code here
}
extension String {
func getMonthDay() -> (Int,Int) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZ"
let date = dateFormatter.date(from: self) ?? Date()
let calendar = Calendar.current
let month = calendar.component(.month, from: date)
let day = calendar.component(.day, from: date)
return (month, day)
}
}

newDateFormatter.string(from: ) is always nil

I am formatting a randomly generated future date but it always returns nil even if the format of dateString is matching and has a value.
But if I try with only "(Date())" instead of newDate, it is successful.
let byDays = Int.random(in: 0...30)
var components = DateComponents()
components.day = byDays
let newDate = String(describing: Calendar.current.date(byAdding: components, to: Date()))
//give the current date output in string
let dateFormatterGet = DateFormatter()
dateFormatterGet.isLenient = true
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
dateFormatterGet.locale = Locale(identifier: "en_US_POSIX")
//describe the new format
guard let date = dateFormatterGet.date(from: newDate) else {
return ""
}
let newDateFormatter = DateFormatter()
newDateFormatter.dateFormat = "MMM dd"
let newStr = newDateFormatter.string(from: date)
print(newStr)
I want the date optional(2019-07-23 17:44:23 +0000) to be printed as Jul 23.
I don't understand the purpose of String(describing: ... You can use the date from the Calendar right away:
func randomFutureDate() -> String? {
let day = Int.random(in: 0...30)
var components = DateComponents()
components.day = day
guard let date = Calendar.current.date(byAdding: components, to: Date()) else {
return nil
}
let newDateFormatter = DateFormatter()
newDateFormatter.dateFormat = "MMM dd"
return newDateFormatter.string(from: date)
}

Convert string of format "19-07-2018 08:10:24" in date and time both different string format

I want to Convert string of format "19-07-2018 08:10:24" in date time format. If the date is today then it should be "02:12 am". If the date is of yesterday then it should be like "Yesterday". Otherwise it should be in "DD/MM/yy" format. Currently I am having the time and date in string formate.
I want the final answer in string type. If the answer is "DD/MM/YY", then it should be in string format.
Use the Calendar date functions:
func format(date: Date) -> String {
let calendar = Calendar.current
if calendar.isDateInToday(date) {
// process your "Today" format
return ...
}
if calendar.isDateInYesterday(date) {
// process your "Yesterday" format
return ...
}
if calendar.isDateInTomorrow(date) {
// process your "Tomorrow" format
return ...
}
// process your "full date/time format"
return ...
}
You can read more about the Calendar functions here: https://developer.apple.com/documentation/foundation/calendar
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"//19-07-2018 08:10:24
let date = dateFormatter.date(from: "15-07-2018 08:10:24")
dateFormatter.dateFormat = "dd/MM/yyyy"
let startDate = dateFormatter.string(from: date!)
let dateToday = (Calendar.current as NSCalendar).date(byAdding: .day, value: 0, to: Date(), options: [])! as Date
dateFormatter.dateFormat = "dd/MM/yyyy"
let strdateToday = dateFormatter.string(from: dateToday1)
let dateYesterday = (Calendar.current as NSCalendar).date(byAdding: .day, value: -1, to: Date(), options: [])! as Date
dateFormatter.dateFormat = "dd/MM/yyyy"
let strdateYesterday = dateFormatter.string(from: dateYesterday1)
if(startDate == strdateToday)
{
dateFormatter.dateFormat = "HH:mm"
let startDate = dateFormatter.string(from: date!)
print(startDate)
}
else if(startDate == strdateYesterday)
{
print("Yesterday")
}
else
{
print(startDate)
}

iOS Swift converting calendar component int month to medium style string month

I want to display calendar in this format
to the user. One option is to use "string range" to get the individual calendar components. The second one is to get it using NSCalendar which to me looks like the better one (is it?). So my code is as below. But there are two problems.
I am not getting the local time form "hour & minute components"
I am getting month in Int. I want it to be in String (month in mediumStyle)
Anyone know how to get what I need? Image attached is what exactly I want to achieve. There I am using three UILabel one for "date", second for "month, year" and third for "time".
Any help would be appreciated.
var inputDateString = "Jun/12/2015 02:05 Am +05:00"
override func viewDidLoad() {
super.viewDidLoad()
let newDate = dateformatterDateString(inputDateString)
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitMonth | .CalendarUnitYear | .CalendarUnitDay, fromDate: newDate!)
let hour = components.hour
let minutes = components.minute
let month = components.month
let year = components.year
let day = components.day
println(newDate)
println(components)
println(day) // 12
println(month) // 6 -----> Want to have "Jun" here
println(year) // 2015
println(hour) // 2 ------> Want to have the hour in the inputString i.e. 02
println(minutes) // 35 ------> Want to have the minute in the inputString i.e. 05
}
func dateformatterDateString(dateString: String) -> NSDate? {
let dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM/dd/yyyy hh:mm a Z"
// dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
dateFormatter.timeZone = NSTimeZone.localTimeZone()
return dateFormatter.dateFromString(dateString)
}
You can use DateFormatter as follow:
extension Formatter {
static let monthMedium: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "LLL"
return formatter
}()
static let hour12: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "h"
return formatter
}()
static let minute0x: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "mm"
return formatter
}()
static let amPM: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "a"
return formatter
}()
}
extension Date {
var monthMedium: String { return Formatter.monthMedium.string(from: self) }
var hour12: String { return Formatter.hour12.string(from: self) }
var minute0x: String { return Formatter.minute0x.string(from: self) }
var amPM: String { return Formatter.amPM.string(from: self) }
}
let date = Date()
let dateMonth = date.monthMedium // "May"
let dateHour = date.hour12 // "1"
let dateMinute = date.minute0x // "18"
let dateAmPm = date.amPM // "PM"
NSDateFormatter has monthSymbols, shortMonthSymbols and veryShortSymbols properties.
So try this:
let dateFormatter: NSDateFormatter = NSDateFormatter()
let months = dateFormatter.shortMonthSymbols
let monthSymbol = months[month-1] as! String // month - from your date components
println(monthSymbol)
I am adding three types. Have a look.
//Todays Date
let todayDate = NSDate()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
let components = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: todayDate)
var (year, month, date) = (components.year, components.month, components.day)
println("YEAR: \(year) MONTH: \(month) DATE: \(date)")
//Making a X mas Yr
let morningOfChristmasComponents = NSDateComponents()
morningOfChristmasComponents.year = 2014
morningOfChristmasComponents.month = 12
morningOfChristmasComponents.day = 25
morningOfChristmasComponents.hour = 7
morningOfChristmasComponents.minute = 0
morningOfChristmasComponents.second = 0
let morningOfChristmas = NSCalendar.currentCalendar().dateFromComponents(morningOfChristmasComponents)!
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.LongStyle
formatter.timeStyle = .MediumStyle
let dateString = formatter.stringFromDate(morningOfChristmas)
print("dateString : \(dateString)")
//Current month - complete name
let dateFormatter: NSDateFormatter = NSDateFormatter()
let months = dateFormatter.monthSymbols
let monthSymbol = months[month-1] as! String
println("monthSymbol : \(monthSymbol)")
Print Results:
YEAR: 2015 MONTH: 10 DATE: 9
dateString : December 25, 2014 at 7:00:00 AM
monthSymbol : October
Update Swift 5.x Solution:
Today is Monday, 20 April, 2020
let date = Date() // get a current date instance
let dateFormatter = DateFormatter() // get a date formatter instance
let calendar = dateFormatter.calendar // get a calendar instance
Now you can get every index value of year, month, week, day everything what you want as follows:
let year = calendar?.component(.year, from: date) // Result: 2020
let month = calendar?.component(.month, from: date) // Result: 4
let week = calendar?.component(.weekOfMonth, from: date) // Result: 4
let day = calendar?.component(.day, from: date) // Result: 20
let weekday = calendar?.component(.weekday, from: date) // Result: 2
let weekdayOrdinal = calendar?.component(.weekdayOrdinal, from: date) // Result: 3
let weekOfYear = calendar?.component(.weekOfYear, from: date) // Result: 17
You can get an array of all month names like:
let monthsWithFullName = dateFormatter.monthSymbols // Result: ["January”, "February”, "March”, "April”, "May”, "June”, "July”, "August”, "September”, "October”, "November”, "December”]
let monthsWithShortName = dateFormatter.shortMonthSymbols // Result: ["Jan”, "Feb”, "Mar”, "Apr”, "May”, "Jun”, "Jul”, "Aug”, "Sep”, "Oct”, "Nov”, "Dec”]
You can format current date as you wish like:
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let todayWithTime = dateFormatter.string(from: date) // Result: "2020-04-20 06:17:29"
dateFormatter.dateFormat = "yyyy-MM-dd"
let onlyTodayDate = dateFormatter.string(from: date) // Result: "2020-04-20"
I think this is the most simpler and updated answer.
Swift 4.x Solution:
//if currentMonth = 1
DateFormatter().monthSymbols[currentMonth - 1]
Answer:
January
let now = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "LLLL"
let nameOfMonth = dateFormatter.string(from: now)

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