I have dateformat string like this "2015-03-09".How do i get next 10 days date from current date?any help will be appreciated.thanks in advance
For a purely Swift 3 solution:
Calendar.current.date(byAdding: .day, value: 10, to: Date())
Here's how to get a date 10 days from now, using built-in date modification method .dateByAddingUnit
If all 10 days (dates) are required, can be looped by "value:10" part and added to array.
var tenDaysfromNow: NSDate {
return NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: 10, toDate: NSDate(), options: [])!
}
print(tenDaysfromNow)
And for Swift3:
var tenDaysfromNow: Date {
return (Calendar.current as NSCalendar).date(byAdding: .day, value: 10, to: Date(), options: [])!
}
You can use the dateByAddingTimeInterval() method for this.
var dateStr = "2015-03-09"
var formatter = NSDateFormatter()
formatter.dateFormat = "YYYY-MM-dd"
var currDate = formatter.dateFromString(dateStr)
for i in 1...10
{
var interval = NSTimeInterval(60 * 60 * 24 * i)
var newDate = currDate?.dateByAddingTimeInterval(interval)
println(newDate)
}
EDIT:
As mentioned by #Martin R in the comments, it'll be better to use dateByAddingComponents() of NSCalendar class:
var calendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
var dateComponent = NSDateComponents()
for i in 1...10
{
dateComponent.day = i
var newDate = calendar?.dateByAddingComponents(dateComponent, toDate: currDate!, options:nil)
println(newDate)
}
There is a function 'dateByAddingTimeInterval()' for an NSDate object. With this, you can create a NSDate from your date string. Then add 10 days = 10*24*60*60 to get next 10 days NSDate value
let today : NSDate = ....
let next10days = today.dateByAddingTimeInterval(10*60*60*24); //interval = seconds
//then you convert back to your date string format if you want, by using NSDateFormatter
To avoid problem with Daylighttime saving (#MartinR):
let cal = NSCalendar(calendarIdentifier: NSGregorianCalendar)
let next10Days = cal.dateByAddingUnit(NSCalendarUnit.DayCalendarUnit, value: 10, toDate: today, options: nil)
Here is a swift 4/5 version of the answer by #MidhunMP
var dateStr = "2015-03-09"
var formatter = DateFormatter()
formatter.dateFormat = "YYYY-MM-dd"
var calendar = Calendar(identifier: .gregorian)
var dateComponent = DateComponents()
if let currDate = formatter.date(from: dateStr) {
for i in 1...10 {
let newDate = calendar.date(byAdding: .day, value: i, to: currDate)
print(newDate)
}
}
For Swift 3:
let now = NSDate()
let plusTen = now.dateByAddingDays(10)
Related
I’m creating a date using NSDateComponents().
let startDate = NSDateComponents()
startDate.year = 2015
startDate.month = 9
startDate.day = 1
let calendar = NSCalendar.currentCalendar()
let startDateNSDate = calendar.dateFromComponents(startDate)!
... now I want to print all dates since the startDate until today, NSDate(). I’ve already tried playing with NSCalendarUnit, but it only outputs the whole difference, not the single dates between.
let unit: NSCalendarUnit = [.Year, .Month, .Day, .Hour, .Minute, .Second]
let diff = NSCalendar.currentCalendar().components(unit, fromDate: startDateNSDate, toDate: NSDate(), options: [])
How can I print all dates between two Dateobjects?
Edit 2019
In the meantime the naming of the classes had changed – NSDate is now just Date. NSDateComponents is now called DateComponents. NSCalendar.currentCalendar() is now just Calendar.current.
Just add one day unit to the date until it reaches
the current date (Swift 2 code):
var date = startDateNSDate // first date
let endDate = NSDate() // last date
// Formatter for printing the date, adjust it according to your needs:
let fmt = NSDateFormatter()
fmt.dateFormat = "dd/MM/yyyy"
// While date <= endDate ...
while date.compare(endDate) != .OrderedDescending {
print(fmt.stringFromDate(date))
// Advance by one day:
date = calendar.dateByAddingUnit(.Day, value: 1, toDate: date, options: [])!
}
Update for Swift 3:
var date = startDate // first date
let endDate = Date() // last date
// Formatter for printing the date, adjust it according to your needs:
let fmt = DateFormatter()
fmt.dateFormat = "dd/MM/yyyy"
while date <= endDate {
print(fmt.string(from: date))
date = Calendar.current.date(byAdding: .day, value: 1, to: date)!
}
Using extension:
extension Date {
static func dates(from fromDate: Date, to toDate: Date) -> [Date] {
var dates: [Date] = []
var date = fromDate
while date <= toDate {
dates.append(date)
guard let newDate = Calendar.current.date(byAdding: .day, value: 1, to: date) else { break }
date = newDate
}
return dates
}
}
Usage:
let datesBetweenArray = Date.dates(from: Date(), to: Date())
Same thing but prettier:
extension Date {
func allDates(till endDate: Date) -> [Date] {
var date = self
var array: [Date] = []
while date <= endDate {
array.append(date)
date = Calendar.current.date(byAdding: .day, value: 1, to: date)!
}
return array
}
}
How to get all dates for next 20 days:
if let date = Calendar.current.date(byAdding: .day, value: 20, to: Date()) {
print(Date().allDates(till: date))
}
Your desired code becomes like
let startDate = NSDateComponents()
startDate.year = 2015
startDate.month = 9
startDate.day = 1
let calendar = NSCalendar.currentCalendar()
let startDateNSDate = calendar.dateFromComponents(startDate)!
var offsetComponents:NSDateComponents = NSDateComponents();
offsetComponents.day = 1
var nd:NSDate = startDateNSDate;
println(nd)
while nd.timeIntervalSince1970 < NSDate().timeIntervalSince1970 {
nd = calendar.dateByAddingComponents(offsetComponents, toDate: nd, options: nil)!;
println(nd)
}
Here is Solution of Print all dates between two Dates (Swift 4 Code)
var mydates : [String] = []
var dateFrom = Date() // First date
var dateTo = Date() // Last date
// Formatter for printing the date, adjust it according to your needs:
let fmt = DateFormatter()
fmt.dateFormat = "yyy-MM-dd"
dateFrom = fmt.date(from: strstartDate)! // "2018-03-01"
dateTo = fmt.date(from: strendDate)! // "2018-03-05"
while dateFrom <= dateTo {
mydates.append(fmt.string(from: dateFrom))
dateFrom = Calendar.current.date(byAdding: .day, value: 1, to: dateFrom)!
}
print(mydates) // Your Result
Output is:
["2018-03-01", "2018-03-02", "2018-03-03", "2018-03-04", "2018-03-05"]
I am using this approach (Swift 3):
import Foundation
class Dates {
static func printDatesBetweenInterval(_ startDate: Date, _ endDate: Date) {
var startDate = startDate
let calendar = Calendar.current
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
while startDate <= endDate {
print(fmt.string(from: startDate))
startDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
}
}
static func dateFromString(_ dateString: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.date(from: dateString)!
}
}
and I am calling this like:
Dates.printDatesBetweenInterval(Dates.dateFromString("2017-01-02"), Dates.dateFromString("2017-01-9"))
The output is:
2017-01-02
2017-01-03
2017-01-04
2017-01-05
2017-01-06
2017-01-07
2017-01-08
2017-01-09
You can use the compactMap operator.
I like to put these functions in an extension so they are reusable.
It's hard to make a range of dates, so I made a range of ints and loop through that.
extension Calendar {
func getDates(_ startDate: Date, _ endDate: Date) -> [Date] {
// make sure parameters are valid
guard startDate < endDate else { print("invalid parameters"); return [] }
// how many days between dates?
let dayDiff = Int(self.dateComponents([.day], from: startDate, to: endDate).day ?? 0)
let rangeOfDaysFromStart: Range<Int> = 0..<dayDiff + 1
let dates = rangeOfDaysFromStart.compactMap{ self.date(byAdding: .day, value: $0, to: startDate) }
return dates
}
}
Your usage could be:
let startDate = Date(dateString: "1/2/2017", format: "M/d/yyyy")
let endDate = Date(dateString: "1/9/2017", format: "M/d/yyyy")
let dates = Calendar.current.getDates(startDate, endDate)
let f = DateFormatter(withFormat: "yyyy-MM-dd", locale: "us_en")
print(dates.compactMap{f.string(from: $0)}.joined(separator: ", "))
output:
"2017-01-02, 2017-01-03, 2017-01-04, 2017-01-05, 2017-01-06, 2017-01-07, 2017-01-08, 2017-01-09"
I need to get the List of dates for the given date of the week.
As an example :
If user select the random date from picker Like 2017-6-7,
I needs to get and display the dates of the week.
[2017-6-4, 2017-6-5, 2017-6-6, 2017-6-7, 2017-6-8, 2017-6-9, 2017-6-10]
I couldn't find any solution on the internet.
Thank you
Try this:
let dateInWeek = Date()//7th June 2017
let calendar = Calendar.current
let dayOfWeek = calendar.component(.weekday, from: dateInWeek)
let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: dateInWeek)!
let days = (weekdays.lowerBound ..< weekdays.upperBound)
.compactMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: dateInWeek) }
print(days)
It will give you this:
4 June 2017(Sunday)
5 June 2017
6 June 2017
7 June 2017
8 June 2017
9 June 2017
10 June 2017(Saturday)
Start fromMonday
The above is default behavior for my calendar that's why it is starting from Sunday.
If you want start from Monday then do this change:
let dayOfWeek = calendar.component(.weekday, from: dateInWeek) - 1
It depends on which locale your calendar is in.
This is a starting point using the date math skills of Calendar
var calendar = Calendar.current
calendar.firstWeekday = 1 // adjust first weekday if necessary
var startOfWeek = Date()
var interval : TimeInterval = 0.0
_ = calendar.dateInterval(of:.weekOfYear, start: &startOfWeek, interval: &interval, for: Date())
for i in 0..<7 {
print(calendar.date(byAdding: .day, value: i, to: startOfWeek)!)
}
You can use this.
let today = Date()
let weekStartDate = today.getWeekStartDate(fromDate: today)
for i in 0..<5 {
let nextDate = weekStartDate?.getNextDay(value: i, currentDate:weekStartDate)
}
func getWeekStartDate(fromDate : Date?) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
if let date = fromDate {
var calendar = Calendar(identifier: .gregorian)
calendar.firstWeekday = 3
var startDate : Date = Date()
var interval : TimeInterval = 0
if calendar.dateInterval(of: .weekOfYear, start: &startDate, interval: &interval, for: date) {
print("Start of week is \(startDate)")
// prints "Start of week is 2017-01-01 06:00:00 +0000"
return startDate
}
}
return nil
}
func getNextDay(value : Int, currentDate : Date?) -> Date? {
let dayComponenet = NSDateComponents()
dayComponenet.day = value
let theCalendar = NSCalendar.current
let nextDate = theCalendar.date(byAdding: dayComponenet as DateComponents, to: currentDate!)
return nextDate
}
Hope this will help!.
I want to print date [1,2,3.... current date] but not getting correct result.
Because when I set first day is "1" in my code, the output in [2,3,4]. And when I set day is "0". It result show correct but show an extra date [1,2,3,4,5]. And today is 4th October 2016, as my time zone.
let date = NSDate()
let components = NSCalendar.currentCalendar().components([.Day , .Month , .Year], fromDate: date)
let year = components.year
let month = components.month
let day = 1 // Output is [2,3,4]
// let day = 0 than o/p [1,2,3,4,5]
dateFormatatter.dateFormat = "MMMM yyyy"
monthNameLabel.text = dateFormatatter.stringFromDate(date)
startDate.year = year
startDate.month = month
startDate.day = day
let startDateNSDate = calendar.dateFromComponents(startDate)!
var dateStart = startDateNSDate // first date
let endDate = NSDate() // last date
dateFormatatter.dateFormat = "dd"
while dateStart.compare(endDate) != .OrderedDescending {
// print(fmt.stringFromDate(date))
// Advance by one day:
dateStart = calendar.dateByAddingUnit(.Day, value: 1, toDate: dateStart, options: [])!
let dateFormat1 = NSDateFormatter()
dateFormat1.dateFormat = "dd-MM-yyyy"
dateArrayCalendar.addObject(dateFormatatter.stringFromDate(dateStart))
dateArrayForCompare.addObject(dateFormat1.stringFromDate(dateStart))
}
And I want result like this [1,2,3,4]
And Same issue Here
let componentsForCompare = calendar.components([.Year, .Month], fromDate: date)
let startOfMonth = calendar.dateFromComponents(componentsForCompare)!
print(startOfMonth)//2016-09-30 18:30:00 +0000
print(dateFormatatter.stringFromDate(startOfMonth)) //01
Its give different Outputs
You need to increment your date at the end of the while loop, rather than at the start:
while dateStart.compare(endDate) != .OrderedDescending {
// print(fmt.stringFromDate(date))
// Advance by one day:
let dateFormat1 = NSDateFormatter()
dateFormat1.dateFormat = "dd-MM-yyyy"
dateArrayCalendar.addObject(dateFormatatter.stringFromDate(dateStart))
dateArrayForCompare.addObject(dateFormat1.stringFromDate(dateStart))
dateStart = calendar.dateByAddingUnit(.Day, value: 1, toDate: dateStart, options: [])!
}
I'm trying to get NSDate from UIDatePicker, but it constantly returns me a date time with trailing 20 seconds. How can I manually set NSDate's second to zero in swift?
extension Date {
var zeroSeconds: Date? {
let calendar = Calendar.current
let dateComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: self)
return calendar.date(from: dateComponents)
}
}
Usage:
let date1 = Date().zeroSeconds
let date2 = Date()
print(date2.zeroSeconds)
From this answer in Swift:
var date = NSDate();
let timeInterval = floor(date .timeIntervalSinceReferenceDate() / 60.0) * 60.0
date = NSDate(timeIntervalSinceReferenceDate: timeInterval)
This is how to do it in Swift 3.
In this example I remove the seconds in the date components:
let date = picker.date
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date)
let fullMinuteDate = calendar.date(from: components)!
Working on a playground:
Truncating a date to a full minute can be done with
let date = NSDate()
let cal = NSCalendar.currentCalendar()
var fullMinute : NSDate?
cal.rangeOfUnit(.CalendarUnitMinute, startDate: &fullMinute, interval: nil, forDate: date)
println(fullMinute!)
Update for Swift 4 and later:
let date = Date()
let cal = Calendar.current
if let fullMinute = cal.dateInterval(of: .minute, for: date)?.start {
print(fullMinute)
}
This method can easily be adapted to truncate to a full hour, day, month, ...
Just reformat the date:
func stripSecondsFromDate(date: NSDate) -> NSDate {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
let str = dateFormatter.stringFromDate(date)
let newDate = dateFormatter.dateFromString(str)!
return newDate
}
import Foundation
let now = Date()
let calendar = Calendar.current
let date = calendar.date(bySettingHour: 0,
minute: 0,
second: 0,
of: now,
direction: .backward)
There is another way, with two more parameters: matchingpolicy and repeatedTimePolicy.
let date = calendar.date(bySettingHour: 0,
minute: 0,
second: 0,
of: now,
matchingPolicy: .strict,
repeatedTimePolicy: .first,
direction: .backward)
To check the result:
let formatter = ISO8601DateFormatter()
formatter.timeZone = TimeZone.current // defaults to GMT
let string = formatter.string(from: date!)
print(string) // 2019-03-27T00:00:00+01:00
I know this doesn't address NSDate directly, but it might be worth anyways - I had this exact same problem with Date and also because I think this might be a more clean approach.
extension Calendar {
/// Removes seconds `Calendar.Component` from a `Date`. If `removingFractional` is `true`, it also
/// removes all fractional seconds from this particular `Date`.
///
/// `removingFractional` defaults to `true`.
func removingSeconds(fromDate date: Date, removingFractional removesFractional: Bool = true) -> Date? {
let seconds = component(.second, from: date)
let noSecondsDate = self.date(byAdding: .second, value: -seconds, to: date)
if removesFractional, let noSecondsDate = noSecondsDate {
let nanoseconds = component(.nanosecond, from: noSecondsDate)
return self.date(byAdding: .nanosecond, value: -nanoseconds, to: noSecondsDate)
}
return noSecondsDate
}
}
Now, to solve your problem, we created the function removingSeconds(fromDate: removingFractional). It's really simple - as you can see in the docs of the function. It removes the .second component and, if removingFractional is true, it also removes any fractional seconds that this Date may have - or the .nanosecond component.
I have made a functioning app and part of it includes formatting the date from a date picker.
I need to change the first day of the week as the week days are being displayed as "1" - "7". However, day 1 is currently Sunday and I need day 1 to be Monday and Sunday as day 7.
The code for my date formatter and picker are below:
var chosenDate = self.datePicker.date
var formatter = NSDateFormatter()
formatter.dateFormat = "ewYY"
let day = formatter.stringFromDate(chosenDate)
let dateResult = "\(day)"
DestViewController.date = dateResult
I got all of my date formatting info from this page:
http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns
I just can't seem to work out how to change this first day of the week?
Many thanks in advance
Mark.
Here is good example in how to manipulate date in swift. you can change the code to fit it better for what you may need, but right now it does what you need.
// Playground - noun: a place where people can play
// Setup the calendar object
let calendar = NSCalendar.currentCalendar()
// Set up date object
let date = NSDate()
// Create an NSDate for the first and last day of the month
let components = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitMonth, fromDate: date)
components.month
// Getting the First and Last date of the month
components.day = 1
let firstDateOfMonth: NSDate = calendar.dateFromComponents(components)!
components.month += 1
components.day = 0
let lastDateOfMonth: NSDate = calendar.dateFromComponents(components)!
var unitFlags = NSCalendarUnit.WeekOfMonthCalendarUnit |
NSCalendarUnit.WeekdayCalendarUnit |
NSCalendarUnit.CalendarUnitDay
let firstDateComponents = calendar.components(unitFlags, fromDate: firstDateOfMonth)
let lastDateComponents = calendar.components(unitFlags, fromDate: lastDateOfMonth)
// Sun = 1, Sat = 7
let firstWeek = firstDateComponents.weekOfMonth
let lastWeek = lastDateComponents.weekOfMonth
let numOfDatesToPrepend = firstDateComponents.weekday - 1
let numOfDatesToAppend = 7 - lastDateComponents.weekday + (6 - lastDateComponents.weekOfMonth) * 7
let startDate: NSDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: -numOfDatesToPrepend, toDate: firstDateOfMonth, options: nil)!
let endDate: NSDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: numOfDatesToAppend, toDate: lastDateOfMonth, options: nil)!
Array(map(0..<42) {
calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: $0, toDate: startDate, options: nil)!
})
"\(components.year)"
//var dateString = stringFromDate(NSDate())// change to your date format
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EE"
var dateString = dateFormatter.stringFromDate(NSDate())
var xdate = dateFormatter.dateFromString(dateString)
//var someDate = dateFormatter.dateString
println(dateString)
this will output::
"Thu"