How to get the last date of the month [duplicate] - swift

This question already has answers here:
first and last day of the current month in swift
(11 answers)
Closed 6 years ago.
I have spent almost a week with unsuccessful tries. How do I get the last date of the current month. For example if it is February in non-leap year then the last date of the month must be 28. How do get the '28'. Another example: If it is January then the last date must be '31'

There are many ways, here are two of them:
Get next 1. and subtract one day
func lastDayOfMonth1() -> Date
{
let calendar = Calendar.current
let components = DateComponents(day:1)
let startOfNextMonth = calendar.nextDate(after:Date(), matching: components, matchingPolicy: .nextTime)!
return calendar.date(byAdding:.day, value: -1, to: startOfNextMonth)!
}
print(lastDayOfMonth1())
Use range(of:in:for:) to get the last day from the range and set the components accordingly:
func lastDayOfMonth2() -> Date
{
let calendar = Calendar.current
let now = Date()
var components = calendar.dateComponents([.year, .month, .day], from: now)
let range = calendar.range(of: .day, in: .month, for: now)!
components.day = range.upperBound - 1
return calendar.date(from: components)!
}
print(lastDayOfMonth2())

Related

Is there a way to get the exact number of weeks in a given year?

Is there a way to get the exact number of weeks in a given year in Swift (e.g. 52 or 53)?
In my region (week starts with Monday, min 4 days in first week), we get 52 weeks (e.g. 2019, 2021-2025) or 53 weeks (e.g. 2020, 2026). That's my basic for the background of my question.
You can get number of weeks by combining Calendar and DateComponents like this:
let year = 2023
let calendar = Calendar.current
let dateComponents = DateComponents(calendar: calendar, year: year)
let date = calendar.date(from: dateComponents)!
let range = calendar.range(of: .weekOfYear, in: .year, for: date)!
let numberOfWeeks = range.count

Swift - Get weekOfYear for a DateComponents entry

I'm facing some problems to get the weekOfYear for a valid DateComponents value. This code
let cal = Calendar.current
let dc = DateComponents(calendar:cal, year: 2023, month: 1, day:12)
let woy = dc.weekOfYear
print("Week of year: \(woy)")
generates
Week of year: nil
as an output.
I've expected 2...
DateComponents is a simple type. It is merely a collection of date components. It does not do date computations like calculating the week of year. That's the job of Calendar. You did not give it a week of year when you initialise the date components, so you get nil when you ask for it.
You can ask the calendar to make a Date out of the DateComponents you have, and ask it what the week of year is:
let cal = Calendar.current
let dc = DateComponents(calendar:cal, year: 2023, month: 1, day:12)
if let date = cal.date(from: dc) {
// prints 2 as expected
print(cal.component(.weekOfYear, from: date))
}

Swift Date Formatter setting an strange day (86) [duplicate]

This question already has answers here:
Swift - Date formatting (DD vs dd)
(3 answers)
Difference between 'YYYY' and 'yyyy' in NSDateFormatter
(4 answers)
Closed 11 months ago.
Building a MacOS app.
Not sure where this is going off the rails. I am trying to get the start and end of the week (Sunday/Saturday) and am using this function:
func getStartAndEndOfWeek(_ dateToCheck:Date) {
//vars
var sundayDiff = 0
var saturdayDiff = 0
//set up a date formatter
var formatter:DateFormatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "YYYY-MM-DD"
//get day of this startDate
let calendar = Calendar.current
let dayComponents = calendar.dateComponents([.weekday], from: Date())
if let dayOfWeek = dayComponents.weekday {
sundayDiff = dayOfWeek - 1
saturdayDiff = 7 - dayOfWeek
}
//get sunday as date
let sunday:Date = Calendar.current.date(byAdding: .day, value: -1 * sundayDiff, to: dateToCheck)!
let saturday:Date = Calendar.current.date(byAdding: .day, value: saturdayDiff, to: dateToCheck)!
let strSunday = formatter.string(from: sunday)
}
printing sunday gives me the correct date (current date is Wednesday, March 30, 2022):
2022-03-27 15:36:45 +0000
converting sunday to a string gives me a day of 86
2022-03-86
What am I doing wrong?
The correct syntax is:
formatter.dateFormat = "yyyy-MM-dd"
Lower or upper case matters here.
The issue there is that D uppercased means the day of the year not the day of the month. Note also that Y uppercased is for yearForWeekOfYear.
If you need further reference you can check this

TimeDifference between minimum date and maximum date

i am completely new in iPhone app development. i am trying to find difference between min_date and max_date in hours. and wants save its value in textfield. Kindly Provide me complete code to find out difference between both of dates. e.g. if min_date: 12/07/1989, 12:00 am and max_date: 13/07/1989,12:00 am , then total hours will be 24 hours. Please provide me code in swift 3.0.
First, use timeIntervalSince to get the difference in seconds:
let timeInterval = max_date.timeIntervalSince(min_date)
Then you can do some maths to calculate the number of hours
let hours = timeInterval / 60 / 60
You can choose to floor or ceiling this number, depending on your requirements.
let previousDate = ...
let now = Date()
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [.month, .day, .hour, .minute, .second]
formatter.maximumUnitCount = 2 // often, you don't care about seconds
if the elapsed time is in months, so you'll set max unit to whatever is
appropriate in your case
let string = formatter.string(from: previousDate, to: now)
let minDate = Date() // your min date
let maxDate = Date() // your max date
let components = Calendar.current.dateComponents([.hour], from: minDate, to: maxDate)
It's the most flexible method for search difference between two dates. You can use other components to search for months, days, years etc.

how to avoid one number when the number is 00 in swift 4? [duplicate]

This question already has answers here:
Leading zeros for Int in Swift
(12 answers)
Closed 5 years ago.
I used the method for current time in my app But the problem is that when the 0 is behind a number the app won't print that like 10:23:4 as you see when the second is 04 the app won't print 04 and print 4 - I know that I can handle this with if else method But I want to know is it possible to fix that in codes or the only way is that? i know that I can use for loop But I want to use one line code to fix that because if use for loop I need to use that for hour and minutes too!
here is my codes
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("Time=\(hour):\(minutes):\(seconds)")
Try this!
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
let hourString = String.init(format: " %02d:%02d:%02d", hour,minutes,seconds)
print(hourString)