Swift: Get 30 days before 'Specific Date'
Here you go:
let toDate = `your date object`
let fromDate = Calendar.current.date(byAdding: .month, value: -1, to: toDate)
or,
// If you want to have exactly 30 days before
let fromDate = Calendar.current.date(byAdding: .day, value: -30, to: toDate)
How to get last 30 dates from date using swift 3.0
You can get last 30 dates from date in this way:
var today = Date()
var dateArray = [String]()
for i in 1...30{
let tomorrow = Calendar.current.date(byAdding: .day, value: -1, to: today)
let date = DateFormatter()
date.dateFormat = "dd-MM-yyyy"
var stringDate : String = date.string(from: today)
today = tomorrow!
dateArray.append(stringDate)
}
print(dateArray)
OUTPUT:
["13-01-2017", "12-01-2017", "11-01-2017", "10-01-2017", "09-01-2017", "08-01-2017", "07-01-2017", "06-01-2017", "05-01-2017", "04-01-2017", "03-01-2017", "02-01-2017", "01-01-2017", "31-12-2016", "30-12-2016", "29-12-2016", "28-12-2016", "27-12-2016", "26-12-2016", "25-12-2016", "24-12-2016", "23-12-2016", "22-12-2016", "21-12-2016", "20-12-2016", "19-12-2016", "18-12-2016", "17-12-2016", "16-12-2016", "15-12-2016"]
Try this it may help you.
How to get 1 hour ago from a date in iOS swift?
For correct calculations involving NSDate that take into account all edge cases of different calendars (e.g. switching between day saving time) you should use NSCalendar class:
Swift 3+
let earlyDate = Calendar.current.date(
byAdding: .hour,
value: -1,
to: Date())
Older
// Get the date that was 1hr before now
let earlyDate = NSCalendar.currentCalendar().dateByAddingUnit(
.Hour,
value: -1,
toDate: NSDate(),
options: [])
How to get previous and next month in calendar-Swift
Try like this.
To get date of next month.
Swift 3 and Swift 4
let nextMonth = Calendar.current.date(byAdding: .month, value: 1, to: Date())
Swift 2.3 or lower
let nextMonth = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: 1, toDate: NSDate(), options: [])
To get date of previous month.
Swift 3
let previousMonth = Calendar.current.date(byAdding: .month, value: -1, to: Date())
Swift 2.3 or lower
let previousMonth = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: -1, toDate: NSDate(), options: [])
Note: To get date of next and previous month I have used todays date, you can use date from which you want next and previous month date, just change NSDate()
with your NSDate
object.
Edit: For continues traveling of next and previous months you need to store one date object currentDate and when you try to get next and previous month use that date object and update it.
For next month.
let currentDate = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: 1, toDate: currentDate, options: [])
For previous month.
let currentDate = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: -1, toDate: currentDate, options: [])
You can also use extension that will make thing easy.
Swift 3
extension Date {
func getNextMonth() -> Date? {
return Calendar.current.date(byAdding: .month, value: 1, to: self)
}
func getPreviousMonth() -> Date? {
return Calendar.current.date(byAdding: .month, value: -1, to: self)
}
}
Swift 2.3 or lower
extension NSDate {
func getNextMonth() -> NSDate?{
return NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: 1, toDate: self, options: [])
}
func getPreviousMonth() -> NSDate?{
return NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: -1, toDate: self, options: [])
}
}
Now just get date from currentDate.
currentDate = currentDate.getNextMonth()
currentDate = currentDate.getPreviousMonth()
How to fix date formatter after adding 30 days to date
There are many issues here and lots of unnecessary code.
- Use the special en_US_POSIX locale when parsing a date string using a fixed format.
- You don't need
stringFromThityDaysBefore
. YourthirtyDaysBeforeToday
is already aDate
30 days afterendingDate
. - Don't set both the
dateFormat
anddate/timeStyle
of a date formatter. Only set one or the other. - At the end, you want a new string representing the new date that is 30 days later. Your code fails because you convert a
Date
to aString
using string interpolation and then you try to parse that string with your 2nd date formatter.
Here's the fixed code:
let timeStarting = "10:50"
let dateStarting = "03/10/2016"
let dateFormater = DateFormatter()
dateFormater.dateFormat = "dd/MM/yyyy HH:mm"
dateFormater.locale = Locale(identifier: "en_US_POSIX")
let timeAndDate = "\(dateStarting) \(timeStarting)"
let endingDate = dateFormater.date(from: timeAndDate)!
//ADD 30 DAYS TO ENDING DATE
let numberOfDays = 30
let thirtyDaysAfter = Calendar.current.date(byAdding: .day, value: numberOfDays, to: endingDate)!
//FORMAT AGAIN TO SHOW THE DATE IN AS (EX.: 13.10.2016)
let dateFormater2 = DateFormatter()
dateFormater2.dateFormat = "dd.MM.yy"
let newDateString = dateFormater2.string(from: thirtyDaysAfter)
The gives the result of 02.11.16
for newDateString
.
One last thing to consider - don't use a dateFormat
on the 2nd date formatter. Use date/timeStyle
. It's always best to use a style for any date you wish to display to the user. This ensures it is formatted best for the user's locale.
Is it possible to subtract days, months or years from current date in swift
You should use Calendar
to do these calculations instead of hard coding 86400
for a day.
if let date = Calendar.current.date(byAdding: .day, value: -7, to: Date()) {
// Use this date
}
How can we get all the days in selected month
You can get the range of day in the month, and map the range initializing a new date using the year and month components of the date combined with the day from the range. I am using noon time because not every date starts at 12am:
extension Date {
func datesInSameMonth(using calendar: Calendar = .current) -> [Date] {
let year = calendar.component(.year, from: self)
let month = calendar.component(.month, from: self)
return calendar.range(of: .day, in: .month, for: self)?.compactMap {
DateComponents(calendar: calendar, year: year, month: month, day: $0, hour: 12).date
} ?? []
}
}
print(Date().datesInSameMonth()) // [2020-09-01 15:00:00 +0000, 2020-09-02 15:00:00 +0000, 2020-09-03 15:00:00 +0000, 2020-09-04 15:00:00 +0000, 2020-09-05 15:00:00 +0000, 2020-09-06 15:00:00 +0000, 2020-09-07 15:00:00 +0000, 2020-09-08 15:00:00 +0000, 2020-09-09 15:00:00 +0000, 2020-09-10 15:00:00 +0000, 2020-09-11 15:00:00 +0000, 2020-09-12 15:00:00 +0000, 2020-09-13 15:00:00 +0000, 2020-09-14 15:00:00 +0000, 2020-09-15 15:00:00 +0000, 2020-09-16 15:00:00 +0000, 2020-09-17 15:00:00 +0000, 2020-09-18 15:00:00 +0000, 2020-09-19 15:00:00 +0000, 2020-09-20 15:00:00 +0000, 2020-09-21 15:00:00 +0000, 2020-09-22 15:00:00 +0000, 2020-09-23 15:00:00 +0000, 2020-09-24 15:00:00 +0000, 2020-09-25 15:00:00 +0000, 2020-09-26 15:00:00 +0000, 2020-09-27 15:00:00 +0000, 2020-09-28 15:00:00 +0000, 2020-09-29 15:00:00 +0000, 2020-09-30 15:00:00 +0000]
swift 3 how to get date for tomorrow and yesterday ( take care special case ) new month or new year
You should use Calendar method date(byAdding component:)
to do your calendrical calculations using noon time. Doing so you don't need to worry about those special cases:
Swift 3 or Later
extension Date {
static var yesterday: Date { return Date().dayBefore }
static var tomorrow: Date { return Date().dayAfter }
var dayBefore: Date {
return Calendar.current.date(byAdding: .day, value: -1, to: noon)!
}
var dayAfter: Date {
return Calendar.current.date(byAdding: .day, value: 1, to: noon)!
}
var noon: Date {
return Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
}
var month: Int {
return Calendar.current.component(.month, from: self)
}
var isLastDayOfMonth: Bool {
return dayAfter.month != month
}
}
Date.yesterday // "Oct 28, 2018 at 12:00 PM"
Date() // "Oct 29, 2018 at 11:01 AM"
Date.tomorrow // "Oct 30, 2018 at 12:00 PM"
Date.tomorrow.month // 10
Date().isLastDayOfMonth // false
Related Topics
Unit Testing Wknavigationdelegate Functions
Load Image from Url on Watchkit
Pod Install Gpuimage Does Not Work
Realm Swift: Always Put Nil Values Last in Sort
Global Var VS Shared Instance Swift
Swiftui: How to Only Run Code When the User Stops Typing in a Textfield
Define Struct That Is Treated Like a Class in Swift
Optional Type 'Bool' Cannot Be Used as a Boolean; Test for '!=Nil' Instead
Cloudkit - "Invalid Bundle Id for Container"
Get Nil When Looking for File in Subdirectory of Main Bundle
Swiftui on MACos - Handle Single-Click and Double-Click at the Same Time
Swift. Declaring Private Functions in Internal Protocol
Ios-Charts Set Maximum Visible X Axis Values
Swiftui Pick a Value from a List with Ontap Gesture
Take Screenshot of Host App Using iOS Share/Action Extensions
How to Reference the View's Window in Swift 3.X Using Storyboards/Cocoa