How to Combine Two Strings (Date & Time) into a New Date in Swift 3

How to combine two strings (date & time) into a new date in Swift 3


let date = "March 24, 2017"
let time = "7:00 AM"

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "MMMM dd, yyyy 'at' h:mm a"
let string = date + " at " + time // "March 24, 2017 at 7:00 AM"
let finalDate = dateFormatter.date(from: string)
print(finalDate?.description(with: .current) ?? "") // "Friday, March 24, 2017 at 7:00:00 AM Brasilia Standard Time"

Is there a more efficient way to combine a date and time in swift 5?

You can join the date & time strings and parse them in one go:

let dateStr = "2020-03-12"
let timeStr = "15:35"

let df = DateFormatter()
df.dateFormat = "y-M-d HH:mm"
let date = df.date(from: dateStr + " " + timeStr)

// prints: 2020-03-12 13:35:00 +0000 (my machine is GMT+2)

Edit: As Leo Dabus said in the comments, a more appropriate format for the provided strings should be yyyy-MM-dd HH:mm (just kept the provided format from the question). The spirit of the answer was not to propose a format but to provide a way to avoid parsing date/time separately.

How to convert 2 Strings (date and time) into one NSDate object in Eastern Time Zone in Swift

I don't think there's anything wrong with the time. EST is -04:00 so 16:30 EST = 20:30 GMT. And you wrote way more code that needed to be:

let scheduledServiceDateStr = "April 21, 2017"
let scheduledServiceTimeStr = "04:30 PM"

let formatter = DateFormatter()
formatter.dateFormat = "MMM dd, yyyy hh:mm a"
formatter.timeZone = TimeZone(identifier: "EST")

if let date = formatter.date(from: scheduledServiceDateStr + " " + scheduledServiceTimeStr) {
print(date)
}

How to combine date and time from two UIDatePickers?


NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:self.datePicker.date];
NSDateComponents *timeComponents = [calendar components:NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:self.timePicker.date];

NSDateComponents *newComponents = [[NSDateComponents alloc]init];
newComponents.timeZone = [NSTimeZone systemTimeZone];
[newComponents setDay:[dateComponents day]];
[newComponents setMonth:[dateComponents month]];
[newComponents setYear:[dateComponents year]];
[newComponents setHour:[timeComponents hour]];
[newComponents setMinute:[timeComponents minute]];

NSDate *combDate = [calendar dateFromComponents:newComponents];

NSLog(@" \ndate : %@ \ntime : %@\ncomDate : %@",self.datePicker.date,self.timePicker.date,combDate);

Problem combining a date and a time into a single NSDate

I was using the wrong calendar components. Here's the corrected function (now for ARC):

+ (NSDate *)combineDate:(NSDate *)date withTime:(NSDate *)time {

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:
NSGregorianCalendar];

unsigned unitFlagsDate = NSYearCalendarUnit | NSMonthCalendarUnit
| NSDayCalendarUnit;
NSDateComponents *dateComponents = [gregorian components:unitFlagsDate
fromDate:date];
unsigned unitFlagsTime = NSHourCalendarUnit | NSMinuteCalendarUnit
| NSSecondCalendarUnit;
NSDateComponents *timeComponents = [gregorian components:unitFlagsTime
fromDate:time];

[dateComponents setSecond:[timeComponents second]];
[dateComponents setHour:[timeComponents hour]];
[dateComponents setMinute:[timeComponents minute]];

NSDate *combDate = [gregorian dateFromComponents:dateComponents];

return combDate;
}

Convert string to date in Swift


  • Convert the ISO8601 string to date

      let isoDate = "2016-04-14T10:44:00+0000"

    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    let date = dateFormatter.date(from:isoDate)!
  • Get the date components for year, month, day and hour from the date

      let calendar = Calendar.current
    let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)
  • Finally create a new Date object and strip minutes and seconds

      let finalDate = calendar.date(from:components)

Consider also the convenience formatter ISO8601DateFormatter introduced in iOS 10 / macOS 10.12:

let isoDate = "2016-04-14T10:44:00+0000"

let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!

How to add days to a date in swift 3

A simple while loop will get you what you need.
Example:

func generateDates(startDate :Date?, addbyUnit:Calendar.Component, value : Int) -> [Date] {

var dates = [Date]()
var date = startDate!
let endDate = Calendar.current.date(byAdding: addbyUnit, value: value, to: date)!
while date < endDate {
date = Calendar.current.date(byAdding: addbyUnit, value: 1, to: date)!
dates.append(date)
}
return dates
}

Edit: Or you can change your implementation slightly if you get your end date in advance

func generateDates(between startDate: Date?, and endDate: Date?, byAdding: Calendar.Component) -> [Date] {

var dates = [Date]()
guard var date = startDate, let endDate = endDate else {
return []
}
while date < endDate {
date = Calendar.current.date(byAdding: byAdding, value: 1, to: date)!
dates.append(date)
}
return dates
}


Related Topics



Leave a reply



Submit