NSDate day of the year (swift)
This is a translation of the answer to How do you calculate the day of the year for a specific date in Objective-C? to Swift.
Swift 2:
let date = NSDate() // now
let cal = NSCalendar.currentCalendar()
let day = cal.ordinalityOfUnit(.Day, inUnit: .Year, forDate: date)
print(day)
Swift 3:
let date = Date() // now
let cal = Calendar.current
let day = cal.ordinality(of: .day, in: .year, for: date)
print(day)
This gives 1
for the first day in the year, and 56 = 31 + 25
for today (Feb 25).
... or do I have to find the number of seconds from Jan 1 to the current date
and divide by the number of seconds in a day
This would be a wrong approach, because a day does not have a fixed
number of seconds (transition from or to Daylight Saving Time).
Swift - Get date from day of year
If you know the year you can get DateComponents date property as follow:
extension Calendar {
static let iso8601 = Calendar(identifier: .iso8601)
}
let now = Date()
let day = Calendar.iso8601.ordinality(of: .day, in: .year, for: now)! // 121
let year = Calendar.iso8601.component(.year, from: now) // 2017
let date = DateComponents(calendar: .iso8601, year: year, day: day).date // "May 1, 2017, 12:00 AM"
or using DateFormatter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy D"
if let date = dateFormatter.date(from: "\(year) \(day)") {
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .short
dateFormatter.string(from: date) // "May 1, 2017, 12:00 AM"
}
Swift - Getting Date from Month, Day, Year Components
You cannot call date(from
on the type. You have to use an instance of the calendar, either the current
calendar
Calendar.current.date(from: DateComponents(year: 2018, month: 1, day: 15))
or a fixed one
let calendar = Calendar(identifier: .gregorian)
calendar.date(from: DateComponents(year: 2018, month: 1, day: 15))
How to get the current time as datetime
Update for Swift 3:
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
I do this:
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute
See the same question in objective-c How do I get hour and minutes from NSDate?
Compared to Nate’s answer, you’ll get numbers with this one, not strings… pick your choice!
Get Date by supplying a month and year
You can use DateComponents initializer to compose a new date just passing the month and year components. Just make sure to pass a calendar as well otherwise the result would be nil. Maybe something like:
extension Date {
static func startOfMonth(for month: Int, of year: Int, using calendar: Calendar = .current) -> Date? {
DateComponents(calendar: calendar, year: year, month: month).date
}
}
Date.startOfMonth(for: 2, of: 2021) // "Feb 1, 2021 at 12:00 AM"
Get last day of the year using Date int swift?
I would get the current year component of the current date. Add one to get next year. Then use that to get the 1st day of that year. Then subtract 1 day to get the last day of the current year.
// Get the current year
let year = Calendar.current.component(.year, from: Date())
// Get the first day of next year
if let firstOfNextYear = Calendar.current.date(from: DateComponents(year: year + 1, month: 1, day: 1)) {
// Get the last day of the current year
let lastOfYear = Calendar.current.date(byAdding: .day, value: -1, to: firstOfNextYear)
}
How to reformat a Date to only Year Month and Day? Swift
Simply create a String
extension and
1. convert String
to Date
with format yyyy-MM-dd HH:mm:ssZZZZ
2. convert Date
to String
with format yyyy-MM-dd
extension String {
var formattedDate: String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZZZZ"
if let date = dateFormatter.date(from: self) {
print(date)
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.string(from: date)
}
return nil
}
}
Example:
let dateStr = "2017-04-10 10:33:42GMT"
let formattedDate = dateStr.formattedDate //Output: "2017-04-10"
how to get year all weeks start date and end date in swift
You can use the suggested extension in this thread: How to get start and end of the week in swift?
To iterate the weeks, and then just print the value with your desired formatter:
let calendar = Calendar.current
let currentYear = calendar.component(.year, from: Date())
let lastDayOfTheYear = calendar.date(from: DateComponents(year: currentYear, month: 12, day: 31))
var currentDate = calendar.date(from: DateComponents(year: currentYear, month: 1, day: 1))
while currentDate! < lastDayOfTheYear! {
let startDay = currentDate!.startOfWeek!.formatted()
let endDay = currentDate!.endOfWeek!.formatted()
print("\(startDay) - \(endDay)")
currentDate = calendar.date(byAdding: .weekOfYear, value: 1, to: currentDate!)
}
extension Date {
func formatted() -> String {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter.string(from: self)
}
var startOfWeek: Date? {
let gregorian = Calendar(identifier: .gregorian)
guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
return gregorian.date(byAdding: .day, value: 1, to: sunday)
}
var endOfWeek: Date? {
let gregorian = Calendar(identifier: .gregorian)
guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
return gregorian.date(byAdding: .day, value: 7, to: sunday)
}
}
prints:
December 30, 2019 - January 5, 2020
January 6, 2020 - January 12, 2020
...
December 21, 2020 - December 27, 2020
December 28, 2020 - January 3, 2021
Related Topics
Font Size on Universal Storyboard
Ios7 App Backward Compatible with iOS5 Regarding Unique Identifier
Uipinchgesturerecognizer. Make Zoom in Location of Fingers, Not Only Center
Choosing Units with Measurementformatter
Facebook App Requests Aren't Shown on iOS Devices
Xcode Duplicate Symbols for Architecture Error After Updating Cocoa Pods
Detect When a Unicode Character Cannot Be Displayed Correctly
Remote Image Size Without Downloading
Perform Action by Clicking on Some Word in Uitextview or Uilabel
How to Query Nearest Users in Firebase with Swift
What's Wrong Here: Instance Member Cannot Be Used on Type
Nsurlsession Delegates Not Called
Add Buttons to Uipickerview - Swift 1.2
Dynamic Collectionviewcell in Tableviewcell Swift
I Added a Localization in Xcode, Removed It and Now My Storyboard Is Gone
Set<Nsobject>' Does Not Have a Member Named 'Anyobject." - Xcode 6.3