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.
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 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.
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).
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With