Conversion From PDT TimeZone to IST Timezone is Incorrect - ios

I had set time to San Carlos California(PDT Timezone) in my I phone, then I am trying to add 30 days which is fine , but when I am trying to convert that Date object to IST Timezone , it is not correct.
11/19/2020 06:46:25
Above one is days added by 30 in todays date, In San Calos(PDT Timezone)
when I am converting that time in IST it is "11/18/2020 at 11:46 PM"
but it should be "11/18/2020 at 19:46"
time is variant..
I am using this to convert time into IST
Convert date to local TimeZone
func convertExpiryToIst(inputFormat: String, outputFormat: String) -> String{
let formatter = DateFormatter()
formatter.dateFormat = inputFormat
formatter.timeZone = TimeZone.current
var date = formatter.date(from: self)
date?.addTimeInterval(TimeInterval(value))
formatter.dateFormat = outputFormat
if date != nil {
print(date)
return formatter.string(from: date!)
}
return self
}

The issue there is that you are adding a time interval to the resulting date. A date has no timezone it is just a point in time. All you need to do is to change the date formatter timezone to the desired one and get the string representation of it.
extension String {
func convertExpiryTo(inputFormat: String, inputTimeZone: String, outputFormat: String, outputTimeZone: String)-> String? {
let formatter = DateFormatter()
formatter.dateFormat = inputFormat
formatter.timeZone = TimeZone(identifier: inputTimeZone)
if let date = formatter.date(from: self) {
// let offset = TimeZone(abbreviation: "IST")!.secondsFromGMT(for: date) - TimeZone(abbreviation: "PDT")!.secondsFromGMT(for: date)
// let hours = Double(offset) / 3600 // 13.5 hours
// dont add the timezone offset
// date?.addTimeInterval(TimeInterval(value))
formatter.dateFormat = outputFormat
// just set a different timezone
formatter.timeZone = TimeZone(identifier: outputTimeZone)
return formatter.string(from: date)
}
return nil
}
}
"11/19/2020 06:46:25".convertExpiry(inputFormat: "MM/dd/yyyy HH:mm:ss", inputTimeZone: "America/Los_Angeles", outputFormat: "MM/dd/yyyy 'at' h:mm a", outputTimeZone: "Asia/Kolkata") // "11/19/2020 at 8:16 PM" = +13.5 hours

Related

I want to convert UTC date to system date based on the system time zone using Swift. It worked for me earlier

func getDateWithoutTimeForDisplay() -> String {
let formatter = DateFormatter()
// formatter.locale = Locale(identifier: "en_US")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.timeZone = TimeZone(identifier: "UTC")
formatter.locale = Locale(identifier: "en_US_POSIX")
let myStringafd = formatter.date(from: self)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
dateFormatter.timeZone = NSTimeZone.local
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
if let myStringafd = myStringafd {
let somedateString = dateFormatter.string(from: myStringafd)
return somedateString
}
return ""
}
this is my code to convert given UTC date to system date based on the local time zone.
The actual problem is, suppose the case "i have the time 1.00 AM on the date 25-08-2020, according to the Indian time zone, ( UTC time is 5.30 lesser than Indian time) the corresponding UTC date is 24-08-2020 due to the time difference with the Indian time". In this case i want to convert the UTC date(Because it is effecting the date to be display for the user) to the current system date.
My system date&time is 25-08-2020 1:00 AM (Indian time)
the corresponding UTC date is 24-08-2020. -5:30 hr
i need to convert the UTC date to the current local time
Try this out:
let currentDate = self.UTCToLocal(date: Date().description) //This will pass system date in UTC format to the function and function will return desired output in local timezone
func UTCToLocal(date: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssz" //The date format should be exact as same as UTC date
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let dt = dateFormatter.date(from: date)
dateFormatter.timeZone = NSTimeZone.local
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss" //The desired date format in which you may want to return the value
return dateFormatter.string(from: dt!)
}
or you can check this post - Returning nil when converting string to date in swift and this link for dateFormatters - https://nsdateformatter.com/

Current date in GMT with DateFormatter [duplicate]

This question already has answers here:
NSDate() or Date() shows the wrong time
(2 answers)
Closed 2 years ago.
I have a problem with the parsing date from the current date to date in GMT timezone.
extension Date {
func getLocalizedDay() -> Date {
let dateFormatter = DateFormatter()
var calendar = Calendar.current
calendar.timeZone = NSTimeZone(name: "GMT")! as TimeZone
dateFormatter.calendar = calendar
dateFormatter.locale = Locale.current
dateFormatter.timeZone = TimeZone(identifier: "GMT")
dateFormatter.dateFormat = "yyy-MM-dd HH:mm:ss"
guard let otpDate = dateFormatter.date(from: dateFormatter.string(from: self)) else { return Date() }
return otpDate
}
}
When I print this I get a correct date but in string
dateFormatter.string(from: self)
When I try to convert it back to date like this:
dateFormatter.date(from: dateFormatter.string(from: self))
I get a date but in UTC...
Does anybody know how to solve this problem?
EDIT:
var dateFromatter = DateFormatter()
var calendar = Calendar.current
calendar.timeZone = NSTimeZone(name: "GMT")! as TimeZone
dateFromatter.calendar = calendar
dateFromatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let now = Date()
let dateInString = dateFromatter.string(from: now)
print(dateInString) // 2020-05-02 13:11:01
print(dateFromatter.date(from: dateInString)!) // 2020-05-02 11:11:01 +0000
The formulae i know is, when u get a Date object it is always in UTC/GMT.
Whe u are using date formatter , Date -> String , sting u will get is related time zone u set.
When u convert String -> Date, Date wu willget in always in UTC/GMT, no matter what time zone u set.
///1 Now is a date in UTC -> converting to UTC date strng right.
print(dateFromatter.string(from: now)) // 2020-05-02 12:53:43
///2 You are converting UTC Date String to Date, which will be in UTC
print(dateFromatter.date(from: dateFromatter.string(from: now))!) // 2020-05-02 10:53:43 +0000

How to get UTC timestamp of a specific hour?

I get the current UTC timestamp using Timezone(abbreviation:"UTC") but can't get the UTC timestamp of some other timestamp.
/*Current local time (4:15 PM) ---> Current UTC (11:15 AM)
Some other time (11:15 PM) ---> UTC (6:15 PM)*/
static func getDateFormat(by date:Date, format:String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
formatter.timeZone = TimeZone(abbreviation: "UTC")
formatter.locale = Locale.current
return formatter.string(from: date)
}
This always give the current UTC.
func convertToUTC(dateToConvert:String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy hh:mm a"
let convertedDate = formatter.date(from: dateToConvert)
formatter.timeZone = TimeZone(identifier: "UTC")
return formatter.string(from: convertedDate!)
}
Your question is not explained properly, though i got your question after reading it multiple times.
You want a function in which you provide a date and that function return you a new date in UTC format.
func convertDateToUTC(date: Date) -> Date {
let calendar = Calendar.current
let dateComponent = calendar.dateComponents([.timeZone], from: date)
//get difference of curent time zone from gmt
//subtract 0 as we want UTC from current time zone
let gmtDiff = 0-dateComponent.timeZone!.secondsFromGMT()
let dateStr = "11:15 PM"
let formatter = DateFormatter()
formatter.dateFormat = "h:mm a"
let date1 = formatter.date(from: dateStr)
let newDate = date1?.addingTimeInterval(TimeInterval(gmtDiff))
return newDate
}
You can format method as your convenience.
We need date components to get time zone difference of current to UTC, then we add that seconds to date and new date we get will be UTC date .

Converting date string with timezone to seconds in swift

I have a date string: "13 December 2017"
a time zone string: "Asia/Kolkata"
What is the way to get Epoch timestamp in seconds in Swift 4.0?
here the solution:
// your input
let dateStr = "13 December 2017"
let timeZoneStr = "Asia/Kolkata"
// building the formatter
let formatter = DateFormatter()
formatter.dateFormat = "d MMMM yyyy"
formatter.timeZone = TimeZone(identifier: timeZoneStr)
// extracting the epoch
let date = formatter.date(from: dateStr) // Dec 13, 2017 at 3:30 AM
let epoch = date?.timeIntervalSince1970
print(epoch ?? "") // 1513103400
for information, this link:
http://userguide.icu-project.org/formatparse/datetime
is an interesting source of date formatters
Updated:
Using Extension:
extension String {
func epoch(dateFormat: String = "d MMMM yyyy", timeZone: String? = nil) -> TimeInterval? {
// building the formatter
let formatter = DateFormatter()
formatter.dateFormat = dateFormat
if let timeZone = timeZone { formatter.timeZone = TimeZone(identifier: timeZone) }
// extracting the epoch
let date = formatter.date(from: self)
return date?.timeIntervalSince1970
}
}
"13 December 2017".epoch(timeZone: "Asia/Kolkata") // 1513103400

Convert NSDate to UTC string and then back to NSDate, the results are not the same

I want to convert NSDate() to UTC date string and then convert this date string back to NSDate, but the results are not the same.
func UTCDateStringFromDate(date: NSDate) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
dateFormatter.timeZone = NSTimeZone(name: "UTC")
dateFormatter.dateFormat = "yyyyMMdd'T'HHmmss'Z'"
let dateString = dateFormatter.stringFromDate(date)
return dateString
}
// outputs: "20150520T030303Z"
let dateString = UTCDateStringFromDate(NSDate())
func dateFromUTCDateString(dateString: String) -> NSDate {
let dateFormatter = NSDateFormatter()
dateFormatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
dateFormatter.timeZone = NSTimeZone(name: "UTC")
dateFormatter.dateFormat = "yyyyMMdd'T'HHmmss'Z'"
return dateFormatter.dateFromString(dateString)!
}
// outputs: "May 20, 2015, 11:03 AM"
dateFromUTCDateString(dateString)
As you can see both outputs, when I convert NSDate() to UTC date string, the result is "20150520T030303Z" and then I convert this date string back to NSDate, the result is "May 20, 2015, 11:03 AM". Why the time is not the same? The first is 03:03 and the second is 11:03?
Because if you just println a NSDate()
It will log date format in GMT,so in your time is UTC + 8
So,your code works just well.
Edit:
There is no timezone of a NSDate,it is just a reference of a absolute time.

Resources