I compute the name of the day like this:
func loadDayName(forDate date: NSDate) -> String{
let myComponents = calendar.components(.Weekday, fromDate: date)
let weekDay = myComponents.weekday
switch weekDay {
case 1:
return "Sunday"
case 2:
return "Monday"
case 3:
return "Tuesday"
case 4:
return "Wednesday"
case 5:
return "Thursday"
case 6:
return "Friday"
case 7:
return "Saturday"
default:
return "Nada"
}
}
It is working fine but I was wondering if Swift comes with some libraries to do that automatically.
Use DateFormatter
Swift 4
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
let dayInWeek = dateFormatter.string(from: date)
Swift3
let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE" // "EE" to get short style
let dayInWeek = dateFormatter.stringFromDate(date) // "Sunday"
Screenshot
If you want to get the array of day names you could use: weekdaySymbols in Calendar()
example:
let calendar = Calendar(identifier: .gregorian)
let days = calendar.weekdaySymbols
There's a new api since iOS 15.
#available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)
extension FormatStyle where Self == Date.FormatStyle {
public static var dateTime: Date.FormatStyle { get }
}
You can now use:
Date().formatted(.dateTime.month(.wide)) // October
Date().formatted(.dateTime.year(.defaultDigits)) // 2022
Date().formatted(.dateTime.weekday(.wide)) // Thursday
Date().formatted(.dateTime.weekday(.abbreviated)) // Thu
Date().formatted(.dateTime.weekday(.narrow)) // T
and so on and so on
You can check also this DateFormatter
let dayNameFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.locale = .current
dateFormatter.calendar = .current
dateFormatter.dateFormat = "cccc"
return dateFormatter
}()
print(dayNameFormatter.string(from: Date())) Prints today's day name 🤪
c - stands for day of the week, good answer, official source
Related
Im trying to print out the name of the day of the week i.e Monday, Tuesday, Wednesday. I currently have this bit of code that does just that. I was wondering if there is a way to get rid of my switch statement and make this better. Thanks!
func getDayOfWeek(_ today: String) -> String? {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
guard let todayDate = formatter.date(from: today) else { return nil }
let myCalendar = Calendar(identifier: .gregorian)
let weekDay = myCalendar.component(.weekday, from: todayDate)
switch weekDay {
case 1:
return "Sunday"
case 2:
return "Monday"
case 3:
return "Tuesday"
case 4:
return "Wednesday"
case 5:
return "Thursday"
case 6:
return "Friday"
case 7:
return "Saturday"
default:
return ""
}
}
getDayOfWeek("2018-3-5")
This prints out "Monday"
You are using the wrong date format. The correct format is "yyyy-M-d". Besides that you can use Calendar property weekdaySymbols which returns the weekday localized.
func getDayOfWeek(_ date: String) -> String? {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-M-d"
formatter.locale = Locale(identifier: "en_US_POSIX")
guard let todayDate = formatter.date(from: date) else { return nil }
let weekday = Calendar(identifier: .gregorian).component(.weekday, from: todayDate)
return Calendar.current.weekdaySymbols[weekday-1] // "Monday"
}
Another option is to use DateFormatter and set your dateFormat to "cccc" as you can see in this answer:
extension Formatter {
static let weekdayName: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "cccc"
return formatter
}()
static let customDate: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-M-d"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
}
extension Date {
var weekdayName: String { Formatter.weekdayName.string(from: self) }
}
Using the extension above your function would look like this:
func getDayOfWeek(_ date: String) -> String? { Formatter.customDate.date(from: date)?.weekdayName }
Playground testing:
getDayOfWeek("2018-3-5") // Monday
Date().weekdayName // Thursday
Use this function:
func DayOfWeek(date: String) -> String?
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-M-d"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
guard let _date = dateFormatter.date(from: date) else { return nil }
let weekday = Calendar(identifier: .gregorian).component(.weekday, from: _date)
return Calendar.current.weekdaySymbols[weekday-1]
}
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")
I have to display date in different format.
For eg.
21st July
I didn't find anything to convert my date in this format. If anyone knows please help me.
Swift
extension Date {
func dateFormatWithSuffix() -> String {
return "dd'\(self.daySuffix())' MMMM yyyy"
}
func daySuffix() -> String {
let calendar = Calendar.current
let components = (calendar as NSCalendar).components(.day, from: self)
let dayOfMonth = components.day
switch dayOfMonth {
case 1, 21, 31:
return "st"
case 2, 22:
return "nd"
case 3, 23:
return "rd"
default:
return "th"
}
}
}
Example
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = date.dateFormatWithSuffix()
print(dateFormatter.string(from: date))
// Output for current date: 22nd May 2019
func setCurrentDate() {
let date = Date()
// Use this to add st, nd, th, to the day
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .ordinal
numberFormatter.locale = Locale.current
//Set other sections as preferred
let monthFormatter = DateFormatter()
monthFormatter.dateFormat = "MMM"
// Works well for adding suffix
let dayFormatter = DateFormatter()
dayFormatter.dateFormat = "dd"
let dayString = dayFormatter.string(from: date)
let monthString = monthFormatter.string(from: date)
// Add the suffix to the day
let dayNumber = NSNumber(value: Int(dayString)!)
let day = numberFormatter.string(from: dayNumber)!
yourDateLabel.text = "\(day) \(monthString)"
}
Label will currently be set to 25th May
You can use NSDateFormatter to display your NSDate. It has properties such as dateStyle, and timeStyle which can easily be altered to get your desired format. If you need more flexibility there's the dateFormat property as well.
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
formatter.stringFromDate(NSDate())
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)
My current code:
if let var timeResult = (jsonResult["dt"] as? Double) {
timeResult = NSDate().timeIntervalSince1970
println(timeResult)
println(NSDate())
}
The results:
println(timeResult) = 1415639000.67457
println(NSDate()) = 2014-11-10 17:03:20 +0000 was just to test to see what NSDate was providing.
I want the first to look like the last. The value for dt = 1415637900.
Also, how can I adjust to time zone? Running on iOS.
You can get a date with that value by using the NSDate(withTimeIntervalSince1970:) initializer:
let date = NSDate(timeIntervalSince1970: 1415637900)
To get the date to show as the current time zone I used the following.
if let timeResult = (jsonResult["dt"] as? Double) {
let date = NSDate(timeIntervalSince1970: timeResult)
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle //Set time style
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle //Set date style
dateFormatter.timeZone = NSTimeZone()
let localDate = dateFormatter.stringFromDate(date)
}
Swift 3.0 Version
if let timeResult = (jsonResult["dt"] as? Double) {
let date = Date(timeIntervalSince1970: timeResult)
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
dateFormatter.timeZone = self.timeZone
let localDate = dateFormatter.string(from: date)
}
Swift 5
if let timeResult = (jsonResult["dt"] as? Double) {
let date = Date(timeIntervalSince1970: timeResult)
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
dateFormatter.timeZone = .current
let localDate = dateFormatter.string(from: date)
}
It's simple to convert the Unix timestamp into the desired format. Lets suppose _ts is the Unix timestamp in long
let date = NSDate(timeIntervalSince1970: _ts)
let dayTimePeriodFormatter = NSDateFormatter()
dayTimePeriodFormatter.dateFormat = "MMM dd YYYY hh:mm a"
let dateString = dayTimePeriodFormatter.stringFromDate(date)
print( " _ts value is \(_ts)")
print( " _ts value is \(dateString)")
For managing dates in Swift 3 I ended up with this helper function:
extension Double {
func getDateStringFromUTC() -> String {
let date = Date(timeIntervalSince1970: self)
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.dateStyle = .medium
return dateFormatter.string(from: date)
}
}
This way it easy to use whenever you need it - in my case it was converting a string:
("1481721300" as! Double).getDateStringFromUTC() // "Dec 14, 2016"
Reference the DateFormatter docs for more details on formatting (Note that some of the examples are out of date)
I found this article to be very helpful as well
Here is a working Swift 3 solution from one of my apps.
/**
*
* Convert unix time to human readable time. Return empty string if unixtime
* argument is 0. Note that EMPTY_STRING = ""
*
* #param unixdate the time in unix format, e.g. 1482505225
* #param timezone the user's time zone, e.g. EST, PST
* #return the date and time converted into human readable String format
*
**/
private func getDate(unixdate: Int, timezone: String) -> String {
if unixdate == 0 {return EMPTY_STRING}
let date = NSDate(timeIntervalSince1970: TimeInterval(unixdate))
let dayTimePeriodFormatter = DateFormatter()
dayTimePeriodFormatter.dateFormat = "MMM dd YYYY hh:mm a"
dayTimePeriodFormatter.timeZone = NSTimeZone(name: timezone) as TimeZone!
let dateString = dayTimePeriodFormatter.string(from: date as Date)
return "Updated: \(dateString)"
}
func timeStringFromUnixTime(unixTime: Double) -> String {
let date = NSDate(timeIntervalSince1970: unixTime)
// Returns date formatted as 12 hour time.
dateFormatter.dateFormat = "hh:mm a"
return dateFormatter.stringFromDate(date)
}
func dayStringFromTime(unixTime: Double) -> String {
let date = NSDate(timeIntervalSince1970: unixTime)
dateFormatter.locale = NSLocale(localeIdentifier: NSLocale.currentLocale().localeIdentifier)
dateFormatter.dateFormat = "EEEE"
return dateFormatter.stringFromDate(date)
}
In Swift 5
Using this implementation you just have to give epoch time as a parameter and you will the output as (1 second ago, 2 minutes ago, and so on).
func setTimestamp(epochTime: String) -> String {
let currentDate = Date()
let epochDate = Date(timeIntervalSince1970: TimeInterval(epochTime) as! TimeInterval)
let calendar = Calendar.current
let currentDay = calendar.component(.day, from: currentDate)
let currentHour = calendar.component(.hour, from: currentDate)
let currentMinutes = calendar.component(.minute, from: currentDate)
let currentSeconds = calendar.component(.second, from: currentDate)
let epochDay = calendar.component(.day, from: epochDate)
let epochMonth = calendar.component(.month, from: epochDate)
let epochYear = calendar.component(.year, from: epochDate)
let epochHour = calendar.component(.hour, from: epochDate)
let epochMinutes = calendar.component(.minute, from: epochDate)
let epochSeconds = calendar.component(.second, from: epochDate)
if (currentDay - epochDay < 30) {
if (currentDay == epochDay) {
if (currentHour - epochHour == 0) {
if (currentMinutes - epochMinutes == 0) {
if (currentSeconds - epochSeconds <= 1) {
return String(currentSeconds - epochSeconds) + " second ago"
} else {
return String(currentSeconds - epochSeconds) + " seconds ago"
}
} else if (currentMinutes - epochMinutes <= 1) {
return String(currentMinutes - epochMinutes) + " minute ago"
} else {
return String(currentMinutes - epochMinutes) + " minutes ago"
}
} else if (currentHour - epochHour <= 1) {
return String(currentHour - epochHour) + " hour ago"
} else {
return String(currentHour - epochHour) + " hours ago"
}
} else if (currentDay - epochDay <= 1) {
return String(currentDay - epochDay) + " day ago"
} else {
return String(currentDay - epochDay) + " days ago"
}
} else {
return String(epochDay) + " " + getMonthNameFromInt(month: epochMonth) + " " + String(epochYear)
}
}
func getMonthNameFromInt(month: Int) -> String {
switch month {
case 1:
return "Jan"
case 2:
return "Feb"
case 3:
return "Mar"
case 4:
return "Apr"
case 5:
return "May"
case 6:
return "Jun"
case 7:
return "Jul"
case 8:
return "Aug"
case 9:
return "Sept"
case 10:
return "Oct"
case 11:
return "Nov"
case 12:
return "Dec"
default:
return ""
}
}
How to call?
setTimestamp(epochTime: time) and you'll get the desired output as a string.
Convert timestamp into Date object.
If timestamp object is invalid then return current date.
class func toDate(_ timestamp: Any?) -> Date? {
if let any = timestamp {
if let str = any as? NSString {
return Date(timeIntervalSince1970: str.doubleValue)
} else if let str = any as? NSNumber {
return Date(timeIntervalSince1970: str.doubleValue)
}
}
return nil
}
Swift:
extension Double {
func getDateStringFromUnixTime(dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = dateStyle
dateFormatter.timeStyle = timeStyle
return dateFormatter.string(from: Date(timeIntervalSince1970: self))
}
}
Anyway #Nate Cook's answer is accepted but I would like to improve it with better date format.
with Swift 2.2, I can get desired formatted date
//TimeStamp
let timeInterval = 1415639000.67457
print("time interval is \(timeInterval)")
//Convert to Date
let date = NSDate(timeIntervalSince1970: timeInterval)
//Date formatting
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd, MMMM yyyy HH:mm:a"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let dateString = dateFormatter.stringFromDate(date)
print("formatted date is = \(dateString)")
the result is
time interval is 1415639000.67457
formatted date is = 10, November 2014 17:03:PM
If you are maximizing the Codable protocol for parsing your JSON data. You could simply make the data type of dt as Date and do:
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
For me: Converting timestamps coming from API to a valid date :
`let date = NSDate.init(fromUnixTimestampNumber: timesTamp /* i.e 1547398524000 */) as Date?`
By using this code you will be able to convert timeStamp to Time and Date
let timeStamp = Date().timeIntervalSince1970
let date = NSDate(timeIntervalSince1970: timeStamp)
let dayTimePeriodFormatter = DateFormatter()
dayTimePeriodFormatter.dateFormat = "dd MMMM,YYYY.hh:mm a"
let dateTimeString = dayTimePeriodFormatter.string(from: date as Date)
let dateTime = dateTimeString.split(separator: ".")
print( "Date = \(dateTime[0])")
print( "Time = \(dateTime[1])")
Output:
Date = 19 January,2022
Time = 10:46 AM