I have two components in my app. A UIDATEPICKER that is set to select the time only, HOURS AND MINUTES. and A calendar (FSCALENDAR 3rd party) that selects the date,month and year for me. I am trying to combine the time selected from a uidatepicker and the date selected from the calendar to create a notification. it is working so far but the hour is 5 hours ahead. i think it is because of the 12 hour format of the uidatepicker. how do i extract the hour component in 24 hours format?
The code below is for extracting the date and time.
class ReminderViewController: UIViewController, FSCalendarDelegate, FSCalendarDataSource {
var reminderDate : String?
var reminderDay : Int?
var reminderMonth : Int?
var reminderYear : Int?
var reminderHour : Int?
var reminderMinute : Int?
#IBOutlet weak var rDatePicker: UIDatePicker!
#IBAction func reminderDatePicker(_ sender: Any) {
var df = DateFormatter()
let date = rDatePicker.date
let dateAsString = df.string(from: date)
let components = Calendar.current.dateComponents([.hour, .minute], from: date)
reminderHour = components.hour!
reminderMinute = components.minute!
}
#IBOutlet weak var doneButton: UIButton!
#IBAction func doneAction(_ sender: Any) {
let calendar = Calendar.current
let totalComponents = NSDateComponents()
totalComponents.day = reminderDay!
totalComponents.hour = reminderHour!
totalComponents.month = reminderMonth!
totalComponents.minute = reminderMinute!
totalComponents.year = reminderYear!
let finalDate = calendar.date(from: totalComponents as DateComponents)
print(finalDate)
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.widthAnchor.constraint(equalToConstant: 500).isActive = true
reminderCalendar.delegate = self
reminderCalendar.dataSource = self
let totalComponents = NSDateComponents()
let calendar = Calendar.current
let date = Date()
let components = Calendar.current.dateComponents([.hour, .minute, .month, .day , .year], from: date)
reminderHour = components.hour!
reminderMinute = components.minute!
reminderMonth = components.month!
reminderDay = components.day!
reminderYear = components.year!
let finalDate = calendar.date(from: components as DateComponents)
print("FINAL" , finalDate)
}
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
print(date)
var df = DateFormatter()
df = DateFormatter()
df.dateFormat = "dd-MM-yyyy"
reminderDate = df.string(from: date)
reminderMonth = Calendar.current.component(.month, from: date)
reminderDay = Calendar.current.component(.day, from: date)
reminderYear = Calendar.current.component(.year, from: date)
print(reminderMonth)
print(reminderYear)
print(reminderDay)
}
}
Get a date and time and Convert it in UST format based on your timezone you are ahead that's why it create issue
func localToUTC(date:String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.calendar = NSCalendar.current
dateFormatter.timeZone = TimeZone.current
let dt = dateFormatter.date(from: date)
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.string(from: dt!)
}
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
print(date)
var df = DateFormatter()
df = DateFormatter()
df.dateFormat = "yyyy:MM:dd:HH:mm:ss"
reminderDate = df.string(from: date)
reminderMonth = Calendar.current.component(.month, from: date)
reminderDay = Calendar.current.component(.day, from: date)
reminderYear = Calendar.current.component(.year, from: date)
print(reminderMonth)
print(reminderYear)
print(reminderDay)
}
Related
I have two dates, date1 and date2 and I want days between date1 and date 2
Example:
let date1 = 28-May-2019,
let date2 = 31-May-2019
The expected output
[Tue, Web Thr, Fri]
let date1Str = "28-May-2019"
let date2Str = "31-May-2019"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.locale = Locale(identifier: "en_US")
var date1 = dateFormatter.date(from:date1Str)!
var date2 = dateFormatter.date(from:date2Str)!
let dayFormatter = DateFormatter()
dayFormatter.dateFormat = "EEE"
while date1 <= date2 {
let dayInWeek = dayFormatter.string(from: date1)
print(dayInWeek)
date1 = Calendar.current.date(byAdding: .day, value: 1, to: date1)!
}
The following code gives you the days between two dates and should account for trickeries with the calendar.
let calendar = Calendar.current
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MMM-yyyy"
let dayFormatter = DateFormatter()
dayFormatter.dateFormat = "EEE"
let dateFrom = dateFormatter.date(from: "28-May-2019")!
let dateTo = dateFormatter.date(from: "31-May-2019")!
var days: [String] = []
var date = dateFrom
while date <= dateTo {
let day = dayFormatter.string(from: date)
days.append(day)
date = calendar.date(byAdding: .day, value: 1, to: date)!
}
print(days)
Try this -
func getWeekdays(dateOne firstDateStr: String, dateTwo secondDateStr: String) -> [String] {
let dateformatter = DateFormatter()
dateformatter.dateFormat = "dd-MMM-yyyy"
guard let firstDate = dateformatter.date(from: firstDateStr),
let secondDate = dateformatter.date(from: secondDateStr) else {
return []
}
let calendar = Calendar.current
let numberOfDays: Int
if firstDate > secondDate {
numberOfDays = (calendar.dateComponents([.day], from: secondDate, to: firstDate).day ?? 0)
} else {
numberOfDays = (calendar.dateComponents([.day], from: firstDate, to: secondDate).day ?? 0)
}
dateformatter.dateFormat = "EEE"
let days = (0...numberOfDays).compactMap { day -> String? in
if let date = calendar.date(byAdding: .day, value: day, to: firstDate) {
return dateformatter.string(from: date)
}
return nil
}
print(days)
return days
}
I'm trying to get the start and end dates of the current month in dd/MM/yyyy format. I tried using extension as answered in this SO Question.But it seems like it's not what I want(the format is different and also it's giving me last month's last date and current month last but one date ). Can some one help me.
Extension Class:
extension Date {
func startOfMonth() -> Date? {
let comp: DateComponents = Calendar.current.dateComponents([.year, .month, .hour], from: Calendar.current.startOfDay(for: self))
return Calendar.current.date(from: comp)!
}
func endOfMonth() -> Date? {
var comp: DateComponents = Calendar.current.dateComponents([.month, .day, .hour], from: Calendar.current.startOfDay(for: self))
comp.month = 1
comp.day = -1
return Calendar.current.date(byAdding: comp, to: self.startOfMonth()!)
}
}
My Struct:
struct Constants{
// keys required for making a Login call (POST Method)
struct LoginKeys {
.....
}
struct RankingKeys {
static let DateFrom = String(describing: Date().startOfMonth()) //giving me 2016-11-30 16:00:00 +0000
static let DateTo = String(describing: Date().endOfMonth())
//2016-12-30 16:00:00 +0000
}
}
Expected Result:
DateFrom = "01/12/2016"
DateTo = "31/12/2016"
You should write this simple code:
let dateFormatter = DateFormatter()
let date = Date()
dateFormatter.dateFormat = "dd-MM-yyyy"
For start Date:
let comp: DateComponents = Calendar.current.dateComponents([.year, .month], from: date)
let startOfMonth = Calendar.current.date(from: comp)!
print(dateFormatter.string(from: startOfMonth))
For end Date:
var comps2 = DateComponents()
comps2.month = 1
comps2.day = -1
let endOfMonth = Calendar.current.date(byAdding: comps2, to: startOfMonth)
print(dateFormatter.string(from: endOfMonth!))
This is what I'm using. Pretty simple but it works.
extension Calendar {
func dayOfWeek(_ date: Date) -> Int {
var dayOfWeek = self.component(.weekday, from: date) + 1 - self.firstWeekday
if dayOfWeek <= 0 {
dayOfWeek += 7
}
return dayOfWeek
}
func startOfWeek(_ date: Date) -> Date {
return self.date(byAdding: DateComponents(day: -self.dayOfWeek(date) + 1), to: date)!
}
func endOfWeek(_ date: Date) -> Date {
return self.date(byAdding: DateComponents(day: 6), to: self.startOfWeek(date))!
}
func startOfMonth(_ date: Date) -> Date {
return self.date(from: self.dateComponents([.year, .month], from: date))!
}
func endOfMonth(_ date: Date) -> Date {
return self.date(byAdding: DateComponents(month: 1, day: -1), to: self.startOfMonth(date))!
}
func startOfQuarter(_ date: Date) -> Date {
let quarter = (self.component(.month, from: date) - 1) / 3 + 1
return self.date(from: DateComponents(year: self.component(.year, from: date), month: (quarter - 1) * 3 + 1))!
}
func endOfQuarter(_ date: Date) -> Date {
return self.date(byAdding: DateComponents(month: 3, day: -1), to: self.startOfQuarter(date))!
}
func startOfYear(_ date: Date) -> Date {
return self.date(from: self.dateComponents([.year], from: date))!
}
func endOfYear(_ date: Date) -> Date {
return self.date(from: DateComponents(year: self.component(.year, from: date), month: 12, day: 31))!
}
}
How to use
let calendar: Calendar = Calendar.current
let startDate = calendar.startOfMonth(Date())
print("startDate :: \(startDate)")
Here is an easy solution in create an extension for Date like following:
extension Date {
func startOfMonth() -> Date {
let interval = Calendar.current.dateInterval(of: .month, for: self)
return (interval?.start.toLocalTime())! // Without toLocalTime it give last months last date
}
func endOfMonth() -> Date {
let interval = Calendar.current.dateInterval(of: .month, for: self)
return interval!.end
}
// Convert UTC (or GMT) to local time
func toLocalTime() -> Date {
let timezone = TimeZone.current
let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}}
And then call with your Date instance like that
print(Date().startOfMonth())
print(Date().endOfMonth())
With Swift 3 & iOS 10 the easiest way I found to do this is Calendar's dateInterval(of:for:):
guard let interval = calendar.dateInterval(of: .month, for: Date()) else { return }
Then use a date formatter to print the dates:
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let dateText = formatter.string(from: interval.start)
This Extension Gives you expected output as per you want
Here I return date
extension NSDate {
func startOfMonth() -> NSDate? {
guard
let cal: NSCalendar = NSCalendar.currentCalendar(),
let comp: NSDateComponents = cal.components([.Year, .Month], fromDate: self) else { return nil }
comp.to12pm()
let dateformattor = NSDateFormatter()
dateformattor.dateFormat = "yyyy-MM-dd"
dateformattor.timeZone = NSTimeZone.localTimeZone()
let dt2 = dateformattor.stringFromDate(cal.dateFromComponents(comp)!)
print(dt2)
dateformattor.dateFormat = "yyyy-MM-dd"
dateformattor.timeZone = NSTimeZone.init(abbreviation: "UTC")
return dateformattor.dateFromString(dt2)
}
func endOfMonth() -> NSDate? {
guard
let cal: NSCalendar = NSCalendar.currentCalendar(),
let comp: NSDateComponents = NSDateComponents() else { return nil }
comp.month = 1
comp.day = -1
comp.to12pm()
let dateformattor = NSDateFormatter()
dateformattor.dateFormat = "yyyy-MM-dd"
dateformattor.timeZone = NSTimeZone.localTimeZone()
let dt2 = dateformattor.stringFromDate(cal.dateByAddingComponents(comp, toDate: self.startOfMonth()!, options: [])!)
dateformattor.dateFormat = "yyyy-MM-dd"
dateformattor.timeZone = NSTimeZone.init(abbreviation: "UTC")
return dateformattor.dateFromString(dt2)
}
}
internal extension NSDateComponents {
func to12pm() {
self.hour = 12
self.minute = 0
self.second = 0
}
}
**OUTPUT :- **
Start Date of Month :- 2016-12-01 00:00:00 +0000
End Date of Month :- 2016-12-31 00:00:00 +0000
For the sake of completeness, the API dateInterval(of:start:interval:for:) of Calendar assigns the start date and interval (in seconds) of the current month to the inout parameters.
The date formatter considers the current time zone.
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "dd/MM/yyyy"
var startDate = Date()
var interval = TimeInterval()
Calendar.current.dateInterval(of: .month, start: &startDate, interval: &interval, for: Date())
let endDate = Calendar.current.date(byAdding: .second, value: Int(interval) - 1, to: startDate)!
let fromDate = formatter.string(from: startDate)
let toDate = formatter.string(from: endDate)
print(fromDate, toDate)
I cannot get the date difference function to work. It says NSDate is not implicitly convertible to 'Date' but I do not see an immediate work around this; using as Date does not work.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var dateLabelOutlet: UILabel!
let currentDate = NSDate()
let dateFormatter = DateFormatter()
let userCalendar = NSCalendar.current
let requestedComponent: NSCalendar.Unit = [
NSCalendar.Unit.month,
NSCalendar.Unit.day,
NSCalendar.Unit.hour,
NSCalendar.Unit.minute,
NSCalendar.Unit.second,
]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func printTime(){
dateFormatter.dateFormat = "dd/MM/yy hh:mm:ss a"
let startTime = NSDate()
let endTime = dateFormatter.date(from: "25/12/16 00:00:00")
let timeDifference = userCalendar.components(requestedComponent, from: startTime, to: endTime!, options: [])
dateLabelOutlet.text = "\(timeDifference.month) Months \(timeDifference.day) Days \(timeDifference.minute) Minutes \(timeDifference.second) Seconds"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Change all of your NSDate to Date, then replace your requestedComponent with this:
let requestedComponent: Set<Calendar.Component> = [ .month, .day, .hour, .minute, .second]
Your difference will be:
let timeDifference = userCalendar.dateComponents(requestedComponent, from: startTime, to: endTime!)
FYI: Your dateFormatter doesn't work with this "25/12/16 00:00:00"
here is your whole class in correct form:
class ViewController: UIViewController {
#IBOutlet weak var dateLabelOutlet: UILabel!
let currentDate = Date()
let dateFormatter = DateFormatter()
let userCalendar = Calendar.current
let requestedComponent: Set<Calendar.Component> = [.month,.day,.hour,.minute,.second]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func printTime() {
dateFormatter.dateFormat = "dd/MM/yy hh:mm:ss"
let startTime = Date()
let endTime = dateFormatter.date(from: "25/12/16 00:00:00")
let timeDifference = userCalendar.dateComponents(requestedComponent, from: startTime, to: endTime!)
dateLabelOutlet.text = "\(timeDifference.month) Months \(timeDifference.day) Days \(timeDifference.minute) Minutes \(timeDifference.second) Seconds"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I think it will be helpfull.It will print all months between from and two dates
let dateFormtter = DateFormatter()
dateFormtter.dateFormat = "yyyy-MM-dd"
let startDate = dateFormtter.date(from: fromTF.text!)
let endDate = dateFormtter.date(from: toTF.text!)
func getMonthAndYearBetween(from start: String, to end: String) - >
[String] {
let format = DateFormatter()
format.dateFormat = "yyyy-MM-dd"
guard let startDate = format.date(from: start),
let endDate = format.date(from: end) else {
return []
}
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(Set([.month,.day]),
from: startDate, to: endDate)
var allDates: [String] = []
let dateRangeFormatter = DateFormatter()
dateRangeFormatter.dateFormat = "yyyy-MM-dd"
for i in 0 ... components.month! {
guard let date = calendar.date(byAdding: .month , value: i, to: startDate) else {
continue
}
let formattedDate = dateRangeFormatter.string(from: date)
allDates += [formattedDate]
print(allDates)
}
return allDates
}
Call above method like this
print(getMonthAndYearBetween(from: fromTF.text!, to:
toTF.text!))
I need to get the age after the datepicker has been used. How would I do this. I can currently get the datepicker to work.
#IBAction func datepickerobj(sender: UITextField) {
let datePickerView:UIDatePicker = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.Date
sender.inputView = datePickerView
datePickerView.addTarget(self, action: Selector("datePickerValueChanged:"), forControlEvents: UIControlEvents.ValueChanged)
}
func datePickerValueChanged(sender:UIDatePicker) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
dateofbirth.text = dateFormatter.stringFromDate(sender.date)
let myDOB = NSCalendar.currentCalendar().dateWithEra(1, year: 1970, month: 09, day: 10, hour: 0, minute: 0, second: 0, nanosecond: 0)!
let myAge = myDOB.age
}
Swift 4.1 / Xcode 9.4.1
func age(dateOfBirth: Date) -> Double {
var ageComponents: DateComponents = Calendar.current.dateComponents([.year], from: dateOfBirth, to: Date())
return Double(ageComponents.year!)
}
This will work fine for u
var birthday: NSDate = ..... //date that comes from date picker
var now: NSDate = NSDate()
var ageComponents: NSDateComponents = NSCalendar.currentCalendar().components(.Year, fromDate: birthday, toDate: now, options: 0)
var age: Int = ageComponents.year()
If u want to formate date you can use DateFormatter
Ex.
let usDateFormat = NSDateFormatter.dateFormatFromTemplate("MMddyyyy", options: 0, locale: NSLocale(localeIdentifier: "en-US"))
//usDateFormat now contains an optional string "MM/dd/yyyy".
let gbDateFormat = NSDateFormatter.dateFormatFromTemplate("MMddyyyy", options: 0, locale: NSLocale(localeIdentifier: "en-GB"))
//gbDateFormat now contains an optional string "dd/MM/yyyy"
formatter.dateFormat = usDateFormat
let usSwiftDayString = formatter.stringFromDate(swiftDay)
// usSwiftDayString now contains the string "06/02/2014".
formatter.dateFormat = gbDateFormat
let gbSwiftDayString = formatter.stringFromDate(swiftDay)
// gbSwiftDayString now contains the string "02/06/2014".
//may be it will help for u
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy"
let currentYear: Int = Int(formatter.stringFromDate(NSDate()))
let dobYear: Int = Int(formatter.stringFromDate(myDOB))
let age: Int = currentYear - dobYear
extension Date {
func age() -> Int {
return Int(Calendar.current.dateComponents([.year], from: self, to: Date()).year!)
}
}
An Date extension version, which let you call the method on any Date var. eg:
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: NSDate.init())
components.day = 31
components.month = 1
components.year = 1979
let date = calendar.dateFromComponents(components)
let years = date.age
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)