Get next 3rd month name from the current month in swift - ios

How can I get The 3rd month names from Current month to Nov. Ex:-if the current month is Nov then I want the month names from Feb. Current month should be the running month.
Question: How to get 3rd month name from the current month?
Can someone please explain to me how to get month name. Any help would be greatly appreciated.
Thanks in advance.

You need to use the Calendar class, e.g.
var now = Date()
var calendar = Calendar.current
if let then = calendar.date(byAdding: .month, value: 3, to: now) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "LLLL"
let monthName = dateFormatter.string(from: then)
print ("\(monthName)")
}
Just keep in mind how calenar arithmetics is handled: if you add "3 months" to let's say Nov 30th, 2019, then you'll get Feb-29th, 2020, although someone might expect March-01, 2020.

//set start & end date in correct format
let startDate = "September"
let strEndDate = "December"
//create date formatter
let formatter = DateFormatter()
formatter.dateFormat = "MMMM"
//convert string into date object
guard let startDate = formatter.date(from: startDate) else {
print("invalid start date")
return
}
//convert string into date object
guard let endDate = formatter.date(from: strEndDate) else {
print("invalid end date time")
return
}
//calculate the month from end date and that should not exceed the start date
for month in 1...6 {
if let dt = Calendar.current.date(byAdding: .month, value: -month, to: endDate) {
if dt.compare(startDate) == .orderedAscending {
break
}
print(formatter.string(from: dt!))
}
}

Related

How do i know if a specific date is a month, or a week to an parent date?

Lets say i have a program that reminds users of their appointments , from the current date until the date of the appointment, i want to find out if a particular date is a week to the appointment or a month to the appointment .
var startDate = startDate
let calendar = Calendar.current
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
while startDate <= endDate {
var newDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
if newDate is a month to endDate {
//schedule reminder
}
if newDate is a week to endDate{
//schedule reminder
}
how can i check if the current date is a week/month to the appointment ?
You don't need to use any date comparison, you can simply generate the notification dates using Calendar.date(byAdding:value:to:) and just passing the correct components. To set the date 1 week/month before endDate, pass -1 to value.
let oneWeekBeforeAppointment = Calendar.current.date(byAdding: .weekOfYear, value: -1, to: endDate)!
let oneMonthBeforeAppointment = Calendar.current.date(byAdding: .month, value: -1, to: endDate)!
Try this to calculate the duration in days
func DateFormat() -> DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
return dateFormatter
}
var appointementDate: Date?
var today = Date()
appointementDate = DateFormat().date(from: "22/02/2020")
today = DateFormat().date(from: DateFormat().string(from: today))!
let timeInterval = Int(exactly: (today.timeIntervalSince(appointementDate!))) ?? 0
print("\(timeInterval/86400) days left")

Difference between two NSDates in Months and Years in Swift iOS

I have to calculate the time between two NSDates in Month + Year.
Example 1:
Start Date: September 2018
End Date: May 2019
So I have to get the difference between these two dates and have to display only last 6 months like below:
April 2019
March 2019
February 2019
January 2019
December 2018
November 2018
Example 2:
Start Date: October 2019
End Date: December 2019
Output should be:
November 2019
October 2019
I can able to to get the difference between two dates in months using below code:
let components = Calendar.current.dateComponents([.weekOfYear, .month], from: subscriptionDate!, to: currentDate!)
Can anyone please help me on this?
Thank you!
You can do this in following way...
//set start & end date in correct format
let strStartDate = "September 2019"
let strEndDate = "December 2019"
//create date formatter
let formatter = DateFormatter()
formatter.dateFormat = "MMMM yyyy"
//convert string into date object
guard let startDate = formatter.date(from: strStartDate) else {
print("invalid start date")
return
}
//convert string into date object
guard let endDate = formatter.date(from: strEndDate) else {
print("invalid end date time")
return
}
//calculate the month from end date and that should not exceed the start date
for month in 1...6 {
if let dt = Calendar.current.date(byAdding: .month, value: -month, to: endDate) {
if dt.compare(startDate) == .orderedAscending {
break
}
print(formatter.string(from: dt!))
}
}
Here's a way to do this:
func monthsBetween(start: DateComponents, end: DateComponents) -> [String] {
let monthsCount = Calendar.current.dateComponents([.month], from: start, to: end).month! - 1
guard monthsCount > 0 else { return [] }
return (1...monthsCount).map {
var monthYear = start
monthYear.month! += $0
let date = Calendar.current.date(from: monthYear)!
let formatter = DateFormatter()
formatter.dateFormat = "MMMM yyyy"
return formatter.string(from: date)
}
}
You should pass in DateComponents with only the month and year components into this method. You can get a DateComponents object with only the month and year from a Date like this.
Calendar.current.dateComponents([.month, .year], from: someDate)

Check for a new month using Date in Swift

I would like to notify the user and reset an aspect of the app once a new month begins. This reset needs to repeats every time the month changes.
Using Swift and have used the DateToolsSwift pod.Date Pod
What's the best way to get this to work
func checkIfNewMonth(newDate: Date, oldDate: Date){
var userCalendar = Calendar.current
userCalendar.timeZone = TimeZone(abbreviation: "UTC")!
let oldComponents = userCalendar.dateComponents([.month, .year], from: oldDate)
let newComponents = userCalendar.dateComponents([.month, .year], from: newDate)
guard let oldCompareDate = userCalendar.date(from: oldComponents) else { return }
guard let newCompareDate = userCalendar.date(from: newComponents) else { return }
if newCompareDate > oldCompareDate {
//New date is a new month
} else if newCompareDate < oldCompareDate {
//New date is an previous month
}
}
Thought I'd post a function that does what the op asked. Just feed in the two dates you want to compare. I think UserDefaults would be a great way of storing the old date as well.
The calendar can tell you the range of the current month. The next month begins at the end of the current month:
let startOfNextMonth = Calendar.current.dateInterval(of: .month, for: Date())?.end
let formatter = DateFormatter()
formatter.dateStyle = .long
print(startOfNextMonth.map(formatter.string(from:)) ?? "not a date")
Simply schedule a UNNotificationRequest for this date.

Date formating, adding days to date

Here is my first question;
import Foundation
let date1 = Date()
let date2 = Date().addingTimeInterval(3600)
if date1 == date2
{
print("equals")
}
else if date1 > date2
{
print("date1 is bigger")
}
else if date1 < date2
{
print("date2 is bigger")
}
It gives below output if i write print("date1") or print("date2")
2018-09-10 08:56:49 +0000
I would like to write the same example but date1 and date2 must include these 2 properties:
format: "dd.MM.yyyy"
locale: "tr_TR"
Beside this, here is my second question:
let date2 = Date().addingTimeInterval(3600)
As you know, this 3600 value adding an hour. How can I add one day? 24*3600? Is there any shortest way?
Try
extension Date {
func addDays(_ days: Int) -> Date {
Calendar.autoupdatingCurrent.date(byAdding: .day, value: days, to: self)!
}
}
Like #Larme said, you might want to look into Calendar.
var dateComponents = DateComponents()
dateComponents.day = 1
guard let date = Calendar.current.date(byAdding: dateComponents, to: Date()) else { // Adding date components to current day.
fatalError("date not found")
}
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short // dd.MM.yyyy
dateFormatter.locale = Locale(identifier: "tr_TR") // Your preferred locale
let dateWithLocale = dateFormatter.string(from: date)
print(date)
Your comparison can be done using the Date objects. Only when you need to print it or use it as a String, you would need to do formatting.
Try this one
let today = Date() // OR your date here
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: today)
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)

issues in comparing Day from Date in swift 4

Comparison is required to check date is past date day.
I have tried with this
let calendar = NSCalendar.current
//Get just MM/dd/yyyy from current date
let components = calendar.dateComponents([], from: Date())
//Convert to NSDate
let pastDates = self.calendar.selectedDates.filter { $0 < calendar.date(from: components as DateComponents)! }
Update the below line to give you a date object,
let components = calendar.dateComponents([.month, .day, .year], from: Date())
Currently you are not providing any date component in the array so you will not get a date object.
I didn't understood what is your question properly, but hope this helps you:
let beforeDateStr = "04/12/2018"
let todayDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let beforeDateFormatted = dateFormatter.date(from: beforeDateStr)
if Calendar.current.compare(todayDate, to: beforeDateFormatted!, toGranularity: .day) == .orderedDescending {
print("before date day is lesser than current date")
} else {
print("before date day is equal or greater than todays date")
}
To find the date is smaller or bigger:
You can use this simple Code:
let differenceBetweenTwoDate = Calendar.current.dateComponents([.day], from: previousDate, to: Date())
if differenceBetweenTwoDate.day! > 0{
print("date is bigger")
}else{
print("date is smaller")
}
Hope it Helps!
This is how you can add hours or days in current date and time -
calendar.date(byAdding: .hour, value: 1, to: currentDate)
calendar.date(byAdding: .day, value: 7, to: currentDate)
And this is how you can compare 2 dates and calculate hours, mins and also days
let calendar = Calendar.current
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let anyDataTime = dateFormatter.date(from: anotherDateTime)
let components = calendar.dateComponents([.minute], from: Date(), to: anyDataTime!)
let hour = (Double(components.minute!) / 60.0).rounded()

Resources