Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the day of the week from a date in Swift

Tags:

ios

swift

I can print the date in this format: Mon, Mar 19, 2018, but I am not sure how to get the Day of the week in this format.

Please help

like image 414
S.S.D Avatar asked Mar 20 '18 10:03

S.S.D


People also ask

How do I print the day in Swift?

If you display a date with print(Date()) you'll get output like 2018-11-17 23:38:02 +0000 (The +0000 bit is the offset from UTC. An offset of 0000 from UTC means the date/time is expressed in the UTC time zone.)

How do I get current week in Swift?

To get the ISO week number (1-53), use calendar. component(. weekOfYear, from: date ) . To get the corresponding four-digit year (e.g. 2022), use calendar.

How do I calculate days between two dates in Swift?

Getting number of days between two dates //MARK:- daysBetween func daysBetween(start: Date, end: Date) -> Int { return Calendar. current. dateComponents([. day], from: start, to: end).


2 Answers

let dateFormatter = DateFormatter()
// uncomment to enforce the US locale
// dateFormatter.locale = Locale(identifier: "en-US") 
dateFormatter.setLocalizedDateFormatFromTemplate("EEE MMM d yyyy")
print(dateFormatter.string(from: Date())) // "Tue, Mar 20, 2018" for en-US locale

Note that I am using a template to provide the exact format, therefore the format will be properly localized in every language.

like image 117
Sulthan Avatar answered Nov 09 '22 20:11

Sulthan


To get the day for a particular date:

let customDateFormatter = DateFormatter()

print(customDateFormatter.weekdaySymbols[Calendar.current.component(.weekday, from: Date())])

// "Wednesday"

source

like image 25
Akshansh Thakur Avatar answered Nov 09 '22 21:11

Akshansh Thakur