Combining time and date in ISO8601 format string using Swift - ios

I have two texfields representing date and time from the date picker, but when I parse the string only the date is displayed. I would like to combine date and time into a string in ISO8601 format (e.g. 2015-06-11T00:00:00.000Z) and send it to the server.

You can do it using NSCalendar method dateBySettingHour as follow:
Xcode 8.2.1 • Swift 3.0.2
let df = DateFormatter()
df.calendar = Calendar(identifier: .iso8601)
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
if let date = df.date(from:"2015-06-11T00:00:00.000Z") {
let hour = 4
if let dateWithTime = Calendar.current.date(bySettingHour: hour, minute: 0, second: 0, of: date) {
let resultString = df.string(from: dateWithTime)
print(resultString) // "2015-06-11T04:00:00.000Z"
}
}

Strings are textual representations of dates and often include an explicit or implicit timezone. NSDate represents a date in UTC.
If you want to add an hour, you convert the string to NSDate, add an hour, convert it to a string. The conversion will take care for example of daylight savings time, where one hour after 2:30am might be 4:30am. Or 2:30am.

Related

DateTime2 formart conversion to Swift Date

I have a date string coming from back-end as "2022-08-16T13:44:11.8743234". Date formatting and conversion is the oldest skill in the book but I cannot figure out why I'm unable to convert that string to a Date object in Swift iOS. I just get nil with any source format I specify.
private func StringToDate(dateString: String) -> Date?
{
let formatter = DateFormatter()
formatter.dateFormat = "YYYY-MM-DDTHH:mm:ss.[nnnnnnn]"
let date = formatter.date(from: dateString)
return date //this is nil every time
}
DateTime2 is a more precise SQL Server extension of the normal C# DateTime, hence why the date string has 7 decimal places afters the seconds.
What am I doing wrong?
In your code the way you are handling the millisecond part is wrong. We use usually .SSS for milliseconds. Take a look at here it shows all the symbols related to date format.
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
let date = dateFormatter.date(from: "2022-08-16T13:44:11.8743234")
print(date)
In addition to that you are using DD for day. DD means the day of the year(numeric). So it should be dd. Same case is applied for the year as well.

Convert UTC time to PST in SWIFT

I need to convert the UTC time to PST
From backed, I get UTC dates like "2021-06-25T07:00:00Z"
I need to show the dates in Hstack from Provided UTC date to the current date.
I write the following code.
Anyone help to me.
func datesRange(from:Date, to:Date)->[Date]{
if from > to {return [Date]()}
var tmpdate = from
var array:[Date] = []
while tmpdate <= to {
array.append(tmpdate)
tmpdate = Calendar.current.date(byAdding: .day,value: 1, to: tmpdate)!
}
return array
}
extension Date{
func convertTimezone(timezone:String)-> Date{
if let targettimeZone = TimeZone(abbreviation: timezone){
let delta = TimeInterval(targettimeZone.secondsFromGMT(for: self) - TimeZone.current.secondsFromGMT(for: self))
return addingTimeInterval(delta)
}else{
return self
}
}
}
I used as follows
func getrangeDays(){
let startday = "2021-06-25T07:00:00Z"
let dateformater = DateFormatter()
dateformater.locale = Locale(identifier: "en_US_POSIX")
dateformater.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
if let date = dateformater.date(from: startday){
let rangedays = datesRange(from:date.convertTimezone(timezone: "PST") , to: Date().convertTimezone(timezone: "PST"))
print(rangedays)
}
}
Your convertTimezone() function does not make sense. It is trying to convert a Date to a different time zone. A Date object does not have a time zone. It is an instant in time, anywhere on the planet. Time zones only make sense when you want to display a Date, or do time zone specific date calculations. (And in that case you want to create a Calendar object and set its time zone to the desired time zone, then use that Calendar for your date calculations.)
Get rid of that function.
Convert your input date string to a Date as you are doing now (although you might want to use an ISO8601DateFormatter rather than a regular date formatter, since those are specifically intended for handling ISO8601 dates.)
Build your date range using your datesRange() function.
Then use a second DateFormatter to display your dates in PST. (Not convert Dates to PST. That doesn't make sense.)

Swift date format returning wrong date

I need to convert my date to string and then string to date. date is "2020-10-17 1:22:01 PM +0000"
Here is my date to string conversion code:
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
let string = formatter.string(from: "2020-10-17 1:22:01 PM +0000")
let createdAT = string
its returning "2020-10-17 18:51:30+05:30"
Here is my string to date conversion code:
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ssZ"
let date = dateFormatter.date(from:date)!
its returning "2020-10-17 1:21:30 PM +0000 - timeIntervalSinceReferenceDate : 624633690.0"
its returning the wrong date after i convert string to date. i need "2020-10-17 18:51:30+05:30" this time to be return when i convert string to date.....
The code in your question is muddled up. You try to convert a string into a string in the first example and something unspecified into a Date in the second example.
Here's how to convert a Date into a String:
import Foundation
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
let string: String = formatter.string(from: Date())
print(string) // prints for example 2020-10-18T10:54:07+01:00
Here's how to convert a string into a date
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ssZ"
let date: Date = formatter.date(from: "2020-10-18 10:59:56+0100")! // In real life, handle the optional properly
print(date) // prints 2020-10-18 09:59:56 +0000
When you print a Date directly, it automatically uses UTC as the time zone. This is why it changed it in the code above.
In the examples, I explicitly specified the type of string and date to show what type they are. Type inference means you can omit these in normal code.
As a general rule when handling dates:
always use Date in your code. Date is a type that stores the number of seconds since Jan 1st 1970 UTC.
Only convert dates to strings when displaying them to the user or communicating with an external system.
When calculating periods etc, always use a Calendar to get things like date components and intervals in units other than seconds. You might think to get "the same time tomorrow" you could just add 24 * 60 * 60 to a Date but in many countries, like mine, that will work on only 363 days in the year. Calendar will correctly handle things like daylight saving and leap years.

how to make 24 hours time format from string in Swift

I want to convert a string that was generated by the user to a Date data type. I want the time to be in 24-hour format
let dateFormatter = DateFormatter()
let timeAsString : String = "22:30"
dateFormatter.dateFormat = "HH:mm"
let timeFromString = dateFormatter.date(from: timeAsString)
result : "Jan 1, 2000 at 10:30 PM"
but the result is in 12-hour format. How can I get 22:30 as a Date data type?
Date has no format, so only can change the string converted from the date
Swift 4
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let newDateString = dateFormatter.string(from: yourDate)
for different date format, you can check nsdateformatter.com
You code is absolutely correct, there no problem in your code. String HH in date format represent 24 hours time display format.
But developer (application) has no control over time format. You can set date format string supporting 24 hours time but if user has (not enabled) turned of 24 hours support from device then it will display time for 12 hours format.
Check your simulator/mac system/iPhone device time format and set it for 24 hours display.
Refer this apple document for 24 hours time support: Date Formatters
The representation of the time may be 13:00. In iOS, however, if the user has switched 24-Hour Time to Off, the time may be 1:00 pm.
func convertToString(of dateTo: Date) -> String {
let dateFormatter = CustomDateFormatter()
//Your New Date format as per requirement change it own
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let newDate: String = dateFormatter.string(from: dateTo) //pass Date here
// print(newDate) //New formatted Date string
return newDate
}

Convert UTC NSDate into Local NSDate not working

I have a string getting from server as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
I convert this string into NSDate by this formate.
class func convertUTCDateToLocateDate(dateStr:String) -> NSDate{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date = dateFormatter.dateFromString(dateStr)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
dateFormatter.timeZone = NSTimeZone.localTimeZone()
let timeStamp = dateFormatter.stringFromDate(date!)
let dateForm = NSDateFormatter()
dateForm.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
dateForm.timeZone = NSTimeZone.localTimeZone()
let dateObj = dateForm.dateFromString(timeStamp)
return dateObj!
}
Suppose the parameter string is "2016-11-05T12:00:00.000Z" but when i convert this string and return a NSDate object it doesn't change the time according to my local time. I get my correct time in the timeStamp string (in above code). But when i try to convert that timeStamp string into NSDate it again shows that date and time which i got as a parameter.
You shouldnt change a NSDate's time. NSDates are just a point in time, counted by seconds. They have no clue about timezones, days, month, years, hours, minutes, seconds,… If printed directly they will always output the time in UTC.
If you change the date to show you the time of your timezone you are actually altering the time in UTC — hence your date becomes representing another point in time, no matter of the timezone.
Keep them intact by not altering them, instead when you need to display them do it via a date formatter.
If you need to do time calculations that are independent of timezones you also can work with NSDateComponents instead.
NSDate doesn't have a timezone. It's a point in time, independent of anything, especially timezones. You cannot "convert a UTC NSDate to a local NSDate", the statement itself doesn't make any sense.

Resources