How to make 30 minute time intervals in swift 2.3 - ios

startTime = 10:00 AM
endTime = 01:00 PM
Now i want to split the time in the interval of 30mins like
10:00 AM 10:30 AM 11:00 AM 11:30 AM .......... till 01:00 PM.
I tried like
let startDate : NSDate! = NSDate()
let time1 : NSDate = startDate.dateByAddingTimeInterval((60*60)/2)
let time2 : NSDate = time1.dateByAddingTimeInterval((60*60)/2)
let time3 : NSDate = time2.dateByAddingTimeInterval((60*60)/2)
let time4 : NSDate = time3.dateByAddingTimeInterval((60*60)/2)
func makeTimeInterval(startTime:String ,endTime:String) -> String
{
let timeFormat = DateFormatter()
timeFormat.dateFormat = "hh:mm a"
var fromTime:NSDate = (timeFormat.date(from:startTime) as NSDate?)!
let toTime:NSDate = (timeFormat.date(from:endTime) as NSDate?)!
var dateByAddingThirtyMinute : NSDate!
let timeinterval : TimeInterval = toTime.timeIntervalSince(fromTime as Date)
let numberOfIntervals : Double = timeinterval / 3600;
var formattedDateString : String!
for _ in stride(from: 0, to: Int(numberOfIntervals * 2), by: 1)
{
dateByAddingThirtyMinute = fromTime.addingTimeInterval(1800)
fromTime = dateByAddingThirtyMinute
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
formattedDateString = dateFormatter.string(from: dateByAddingThirtyMinute! as Date) as String?
print("Time after 30 min = \(formattedDateString)")
}
return formattedDateString
}
Tried those things and i got like 10:10,10:40..etc
how to make 30 min round of interval like 10:00,10:30...etc
Thanks in advance

Use the below function if user enters anytime less than 30 than it will start with very next 30 min e.g 10:20, start from 10:30. And if user give time greater than 30 then very time will be 00 e.g 10:45, start from 11:00.
func makeTimeInterval(startTime:String ,endTime:String) -> String
{
var arr = startTime.components(separatedBy: " ")[0].components(separatedBy: ":")
let str = arr[1] as String
if (Int(str)! > 0 && Int(str)! < 30){
arr[1] = "00"
}
else if(Int(str)! > 30){
arr[1] = "30"
}
let startT:String = "\(arr.joined(separator: ":")) \(startTime.components(separatedBy: " ")[1])"
let timeFormat = DateFormatter()
timeFormat.dateFormat = "hh:mm a"
var fromTime:NSDate = (timeFormat.date(from:startT) as NSDate?)!
let toTime:NSDate = (timeFormat.date(from:endTime) as NSDate?)!
var dateByAddingThirtyMinute : NSDate!
let timeinterval : TimeInterval = toTime.timeIntervalSince(fromTime as Date)
let numberOfIntervals : Double = timeinterval / 3600;
var formattedDateString : String!
for _ in stride(from: 0, to: Int(numberOfIntervals * 2), by: 1)
{
dateByAddingThirtyMinute = fromTime.addingTimeInterval(1800)
fromTime = dateByAddingThirtyMinute
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
formattedDateString = dateFormatter.string(from: dateByAddingThirtyMinute! as Date) as String?
print("Time after 30 min = \(formattedDateString)")
}
return formattedDateString
}

You can user Calendar Components to set minutes 00 and then calculate intervals:
func getIntervals(start: String, end: String)->[Date]{
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm a"
var fromDate = formatter.date(from: start)!
let calendar = Calendar(identifier: .gregorian)
let component = calendar.dateComponents([.hour, .minute], from: fromDate)
fromDate = calendar.date(bySettingHour: component.hour!, minute: 0, second: 0, of: fromDate)!
let thirtyMin: TimeInterval = 1800
let endDate = formatter.date(from: end)!
var intervals = Int(endDate.timeIntervalSince(fromDate)/thirtyMin)
intervals = intervals < 0 ? 0 : intervals
var dates = [Date]()
for x in 0...intervals{
let date = fromDate.addingTimeInterval(TimeInterval(x)*thirtyMin)
dates.append(date)
}
return dates
}
let timeIntervals = getIntervals(start: "10:10 am", end: "1:40 pm")

You can use NSDateComponents class. This class allow to get some date units. You can get minutes and hours values from the date and round the minutes to nearest "good" value (sometimes you should be change hours also).
After that you can get new date with new values of hours and minutes.
Don't forget about a time zone.
NSDate* date = [NSDate date]; //start date
NSCalendar* calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents* components = [calendar components:(NSCalendarUnitMinute | NSCalendarUnitHour) fromDate:date];
NSInteger minutes = [components minute];
NSInteger hours = [components hour];
NSInteger nearestGoodMinutes = [self _nearestGoodMinutesForMinutes:minutes];
BOOL shouldIncHours = [self _shouldINcHoursForMinutes:minutes];
if (shouldIncHours)
{
hours++;
}
NSDate* dateWithGoodHours = [calendar dateBySettingUnit:NSCalendarUnitHour value:hours ofDate:date options:kNilOptions];
NSDate* goodDate = [calendar dateBySettingUnit:NSCalendarUnitMinute value:nearestGoodMinutes ofDate:dateWithGoodHours options:kNilOptions];
Some explanation. NSDate does not contain any date components. Date components depend on current callendar. Also values of the components depent on current time zone. If you create NSCalendar with identifier, you will get calendar in current time zone. The time zone should be same with time zone that you use for displaying of the date to the user.
P.S.
You can do it only for the start date.

func format(minute: Int) {
let h = minute / 60
let m = minute % 60
timeLabel.text = "\(h.padZero()):\(m.padZero())"
}
private extension Int {
func padZero() -> String {
return String(format: "%02d", self)
}
}
Refered to this post https://github.com/onmyway133/blog/issues/340

Related

Creating a simple countdown to date in Swift 4

I'm working on a very simple app that counts down to a date. I found several tutorials but nothing in Swift 4. It seems like a lot has changed as I keep getting compiler errors.
Here is my code:
class ViewController: UIViewController {
#IBOutlet weak var CountdownText: UILabel!
let formatter = DateFormatter()
let userCalendar = NSCalendar.current
let requestedComponent: NSCalendar.Unit = [
NSCalendar.Unit.month,
NSCalendar.Unit.day,
NSCalendar.Unit.hour,
NSCalendar.Unit.minute,
NSCalendar.Unit.second,
]
func printTime()
{
formatter.dateFormat = "MM/dd/yy hh:mm:ss a"
let startTime = NSDate()
let endTime = formatter.date(from: "12/03/18 2:00:00 p")
func timeDifference (requestedComponent: NSCalendar.Unit, from: startTime, to: endTime!, options: [NSCalendar.Options]) {}
CountdownText.text = "\(timeDifference.day) Days \(timeDifference.minute) Minutes \(timeDifference.second) Seconds"
}
}
My errors are:
Use of undeclared type 'startTime'
Use of undeclared type 'endTime'
How to use
Copy the Code to your specific View Controller
Change the value of variable dateString with your date in the format
Date Format "< Month > < date >, < year > < hour >:< minute >:< second >"
Ex. "March 4, 2018 13:20:10"
Code
The below code will be useful for achieving a countdown timer of your custom date.
//
// DateCountDownTimer.swift
// CountDownTimerLearning
//
// Created by ThomasVEK on 04/03/18.
// Copyright © 2018 TVEK Solutions. All rights reserved.
//
import Foundation
func defaultUpdateActionHandler(string:String)->(){
}
func defaultCompletionActionHandler()->(){
}
public class DateCountDownTimer{
var countdownTimer: Timer!
var totalTime = 60
var dateString = "March 4, 2018 13:20:10" as String
var UpdateActionHandler:(String)->() = defaultUpdateActionHandler
var CompletionActionHandler:()->() = defaultCompletionActionHandler
public init(){
countdownTimer = Timer()
totalTime = 60
dateString = "March 4, 2018 13:20:10" as String
UpdateActionHandler = defaultUpdateActionHandler
CompletionActionHandler = defaultCompletionActionHandler
}
public func initializeTimer(pYear:Int, pMonth:String, pDay:Int, pHour:Int, pMin:Int, pSec:Int){
self.dateString = "\(pMonth) \(pDay), \(pYear) \(pHour):\(pMin):\(pSec)" as String
// Setting Today's Date
let currentDate = Date()
// Setting TargetDate
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm:ss"
dateFormatter.timeZone = NSTimeZone.local
let targedDate = dateFormatter.date(from: dateString) as! Date
// Calculating the difference of dates for timer
let calendar = Calendar.current.dateComponents([.day, .hour, .minute, .second], from: currentDate, to: targedDate)
let days = calendar.day!
let hours = calendar.hour!
let minutes = calendar.minute!
let seconds = calendar.second!
totalTime = hours * 60 * 60 + minutes * 60 + seconds
totalTime = days * 60 * 60 * 24 + totalTime
}
func numberOfDaysInMonth(month:Int) -> Int{
let dateComponents = DateComponents(year: 2015, month: 7)
let calendar = Calendar.current
let date = calendar.date(from: dateComponents)!
let range = calendar.range(of: .day, in: .month, for: date)!
let numDays = range.count
print(numDays)
return numDays
}
public func startTimer(pUpdateActionHandler:#escaping (String)->(),pCompletionActionHandler:#escaping ()->()) {
countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
self.CompletionActionHandler = pCompletionActionHandler
self.UpdateActionHandler = pUpdateActionHandler
}
#objc func updateTime() {
self.UpdateActionHandler(timeFormatted(totalTime))
if totalTime > 0 {
totalTime -= 1
} else {
endTimer()
}
}
func endTimer() {
self.CompletionActionHandler()
countdownTimer.invalidate()
}
func timeFormatted(_ totalSeconds: Int) -> String {
let seconds: Int = totalSeconds % 60
let minutes: Int = (totalSeconds / 60) % 60
let hours: Int = (totalSeconds / 60 / 60) % 24
let days: Int = (totalSeconds / 60 / 60 / 24)
return String(format: "%dD %02dH %02dM %02dS", days, hours, minutes, seconds)
}
}
You have specified timeDifference function inside printTime() function and in timeDifference() function you have defined from and to parameters which ones types are startTime and endTime which ones are not types. Replace them with NSDate like:
func timeDifference (requestedComponent: NSCalendar.Unit, from: NSDate, to: NSDate, options: [NSCalendar.Options]) {}
and then call this function with startTime and ednTime variables that you have defined.
Also I think that you should define timeDifference function outside of printTime function.

Date not getting correctly using NSDate In Swift

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: [])!
}

Apple Swift: how to get current seconds in 1/100 or 1/1000?

func updateTime() {
var date = NSDate()
var calendar = NSCalendar.currentCalendar()
var components = calendar.components(.CalendarUnitSecond, fromDate: date)
var hour = components.hour
var minutes = components.minute
var seconds = components.second
counterLabel.text = "\(seconds)"
var myIndicator = counterLabel.text?.toInt()
if myIndicator! % 2 == 0 {
// do this
} else {
// do that
}
}
I'd like to know how I can change this code so I get 1/10 or 1/100 or 1/1000 of a second to display in counterlabel.text.
Just can't figure it out... thanks!
There is a calendar unit for nanoseconds:
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitNanosecond, fromDate: date)
let nanoSeconds = components.nanosecond
Update for Swift 3
let date = Date()
let calendar = NSCalendar.current
let components = calendar.dateComponents([.nanosecond], from: date)
let nanoSeconds = components.nanosecond
This gives the fractional part of the seconds in units of 10-9 seconds.
For milliseconds, just divide this value by 106:
let milliSeconds = nanoSeconds / 1_000_000
Alternatively, if you just want to display the fractional
seconds, use a NSDateFormatter and the SSS format. Example:
let fmt = NSDateFormatter()
fmt.dateFormat = "HH:mm:ss.SSS"
counterLabel.text = fmt.stringFromDate(date)
Update for Swift 3
let fmt = DateFormatter()
fmt.dateFormat = "HH:mm:ss.SSS"
counterLabel.text = fmt.stringFromDate(date)

How to change the first day of week in Swift

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"

How to add one month to an NSDate?

How To Add Month To NSDate Object?
NSDate *someDate = [NSDate Date] + 30Days.....;
You need to use NSDateComponents:
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setMonth:1];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *newDate = [calendar dateByAddingComponents:dateComponents toDate:originalDate options:0];
[dateComponents release]; // If ARC is not used, release the date components
With iOS 8 and OS X 10.9 you can add NSCalendarUnits using NSCalendar:
Objective-C
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *someDate = [cal dateByAddingUnit:NSCalendarUnitMonth value:1 toDate:[NSDate date] options:0];
Swift 3
let date = Calendar.current.date(byAdding: .month, value: 1, to: Date())
Swift 2
let cal = NSCalendar.currentCalendar()
let date = cal.dateByAddingUnit(.Month, value: 1, toDate: NSDate(), options: [])
For swift 3.0
extension Date {
func addMonth(n: Int) -> Date {
let cal = NSCalendar.current
return cal.date(byAdding: .month, value: n, to: self)!
}
func addDay(n: Int) -> Date {
let cal = NSCalendar.current
return cal.date(byAdding: .day, value: n, to: self)!
}
func addSec(n: Int) -> Date {
let cal = NSCalendar.current
return cal.date(byAdding: .second, value: n, to: self)!
}
}
For example, to add 3 months to the current date in Swift:
let date = NSCalendar.currentCalendar().dateByAddingUnit(.MonthCalendarUnit, value: 3, toDate: NSDate(), options: nil)!
In Swift 2.0:
let date = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: 3, toDate: NSDate(), options: [])
The new OptionSetType structure of NSCalendarUnit lets you more simply specify .Month
Parameters that take OptionSetType (like the options: parameter, which takes NSCalendarOptions) can't be nil, so pass in an empty set ([]) to represent "no options".
In Swift 2.0
let startDate = NSDate()
let dateComponent = NSDateComponents()
dateComponent.month = 1
let cal = NSCalendar.currentCalendar()
let endDate = cal.dateByAddingComponents(dateComponent, toDate: startDate, options: NSCalendarOptions(rawValue: 0))
FOR SWIFT 3.0
here is function , you can reduce days , month ,day by any count
like for example here , i have reduced the current system date's year by 100 year , you can do it for day , month also
just set the counter and then store the values in array , and do whatever you want to do with that array
func currentTime(){
let date = Date()
let calendar = Calendar.current
var year = calendar.component(.year, from: date)
let month = calendar.component(.month, from: date)
let day = calendar.component(.day, from: date)
let pastyear = year - 100
var someInts = [Int]()
printLog(msg: "\(day):\(month):\(year)" )
for _ in pastyear...year {
year -= 1
print("\(year) ")
someInts.append(year)
}
print(someInts)
}
Other answers work fine if your desired behaviour is adding a month and allowing for daylight savings time. This produces results such that:
01/03/2017 00:00 + 1 month -> 31/03/2017 23:00
01/10/2017 00:00 + 1 month -> 01/11/2017 01:00
However I wanted to ignore the hour lost or gained by DST, such that:
01/03/2017 00:00 + 1 month -> 01/04/2017 00:00
01/10/2017 00:00 + 1 month -> 01/11/2017 00:00
So I check if a DST boundary is passed, and if so either add or subtract an hour accordingly:
func offsetDaylightSavingsTime() -> Date {
// daylightSavingTimeOffset is either + 1hr or + 0hr. To offset DST for a given date, we need to add an hour or subtract an hour
// +1hr -> +1hr
// +0hr -> -1hr
// offset = (daylightSavingTimeOffset * 2) - 1 hour
let daylightSavingsTimeOffset = TimeZone.current.daylightSavingTimeOffset(for: self)
let oneHour = TimeInterval(3600)
let offset = (daylightSavingsTimeOffset * 2) - oneHour
return self.addingTimeInterval(offset)
}
func isBetweeen(date date1: Date, andDate date2: Date) -> Bool {
return date1.compare(self).rawValue * self.compare(date2).rawValue >= 0
}
func offsetDaylightSavingsTimeIfNecessary(nextDate: Date) -> Date {
if let nextDST = TimeZone.current.nextDaylightSavingTimeTransition(after: self) {
if nextDST.isBetweeen(date: self, andDate: nextDate){
let offsetDate = nextDate.offsetDaylightSavingsTime()
let difference = offsetDate.timeIntervalSince(nextDate)
return nextDate.addingTimeInterval(difference)
}
}
return nextDate
}
func dateByAddingMonths(_ months: Int) -> Date? {
if let dateWithMonthsAdded = Calendar.current.date(byAdding: .month, value: months, to: self) {
return self.offsetDaylightSavingsTimeIfNecessary(nextDate: dateWithMonthsAdded)
}
return self
}
Test:
func testDateByAddingMonths() {
let date1 = "2017-01-01T00:00:00Z".asDate()
let date2 = "2017-02-01T00:00:00Z".asDate()
let date3 = "2017-03-01T00:00:00Z".asDate()
let date4 = "2017-04-01T00:00:00Z".asDate()
let date5 = "2017-05-01T00:00:00Z".asDate()
let date6 = "2017-06-01T00:00:00Z".asDate()
let date7 = "2017-07-01T00:00:00Z".asDate()
let date8 = "2017-08-01T00:00:00Z".asDate()
let date9 = "2017-09-01T00:00:00Z".asDate()
let date10 = "2017-10-01T00:00:00Z".asDate()
let date11 = "2017-11-01T00:00:00Z".asDate()
let date12 = "2017-12-01T00:00:00Z".asDate()
let date13 = "2018-01-01T00:00:00Z".asDate()
let date14 = "2018-02-01T00:00:00Z".asDate()
var testDate = "2017-01-01T00:00:00Z".asDate()
XCTAssertEqual(testDate, date1)
testDate = testDate.dateByAddingMonths(1)!
XCTAssertEqual(testDate, date2)
testDate = testDate.dateByAddingMonths(1)!
XCTAssertEqual(testDate, date3)
testDate = testDate.dateByAddingMonths(1)!
XCTAssertEqual(testDate, date4)
testDate = testDate.dateByAddingMonths(1)!
XCTAssertEqual(testDate, date5)
testDate = testDate.dateByAddingMonths(1)!
XCTAssertEqual(testDate, date6)
testDate = testDate.dateByAddingMonths(1)!
XCTAssertEqual(testDate, date7)
testDate = testDate.dateByAddingMonths(1)!
XCTAssertEqual(testDate, date8)
testDate = testDate.dateByAddingMonths(1)!
XCTAssertEqual(testDate, date9)
testDate = testDate.dateByAddingMonths(1)!
XCTAssertEqual(testDate, date10)
testDate = testDate.dateByAddingMonths(1)!
XCTAssertEqual(testDate, date11)
testDate = testDate.dateByAddingMonths(1)!
XCTAssertEqual(testDate, date12)
testDate = testDate.dateByAddingMonths(1)!
XCTAssertEqual(testDate, date13)
testDate = testDate.dateByAddingMonths(1)!
XCTAssertEqual(testDate, date14)
}
For completeness, the .asDate() method I'm using
extension String {
static let dateFormatter = DateFormatter()
func checkIsValidDate() -> Bool {
return self.tryParseToDate() != nil
}
func tryParseToDate() -> Date? {
String.dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
return String.dateFormatter.date(from: self)
}
func asDate() -> Date {
return tryParseToDate()!
}
}
Do you want to add a "month" or exactly 30 days or one day or one year based on user selecting automatically calculation to date.
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]
init];
[dateFormatter setDateFormat:#"YYYY-MM-dd HH:mm:ss"];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:[NSDate date]];
NSDateComponents *dayComponent = [[NSDateComponents alloc]
init];
int changeid = [here number of days intValue];
dayComponent.hour = changeid;
NSCalendar *theCalendar = [NSCalendar currentCalendar];
NSDate *nextDate = [theCalendar
dateByAddingComponents:dayComponent toDate:[dateFormatter
dateFromString:self.fromDateTF.text] options:0];
NSLog(#"nextDate: %# ...", nextDate);
[self.toDateTF setText:[dateFormatter
stringFromDate:nextDate]];
////month
Do you want to add a "month" or exactly 30 days? If it's 30 days, you do it like this:
// get a date
NSDate *date = [NSDate dateWithNaturalLanguageString:#"2011-01-02"];
// add 30 days to it (in seconds)
date = [date dateByAddingTimeInterval:(30 * 24 * 60 * 60)];
NSLog(#"%#", date); // 2011-02-01
Note: this will not take daylight savings time transitions or leap seconds into account. Use #TheEye's answer if you need that

Resources