Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

date

swift

I am trying to combine two date strings into a format that will allow for a new single date. The first string is a .long style format string. The second string is just a time string. The values look like this:

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

I Need to combine these strings to form a new date that works as iOS swift date. I have tried various DateFormatters and merging the strings together but the combination of .Long for date and .short for time does not seem to work.

like image 386
iOS4Fun Avatar asked Mar 24 '17 19:03

iOS4Fun


People also ask

How do you concatenate text and date?

Suppose you want to create a grammatically correct sentence from several columns of data for a mass mailing or format dates with text without affecting formulas that use those dates. To combine text with a date or time, use the TEXT function and the & (ampersand) operator.

How do I combine date and text in Excel?

How to Combine text with Date & Time here is the solution. Enter this formula =Concatenate(A3,” “,TEXT(B3,”mm/dd/yyyy”) into a blank cell besides your data. Or alternatively can use the second formula as =A4&” “&TEXT(B4,”dd/mm/yyyy”) into a black cell besides your data.

How do you combine dates in Excel?

Select a cell that you will place the date, type this formula =DATE(A2,B2,C2) ,A2, B2 and C2 are the cells you need to combine, press Enter key, and drag fill handle down to the cells which need to combine to dates. Tip: if the year is not complete, you can use this formula =DATE(20&A2,B2,C2).

How do you combine strings?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.


1 Answers

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"
like image 133
Leo Dabus Avatar answered Sep 28 '22 08:09

Leo Dabus