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 .
Related
How to separate hour and minute from date .
let StDate = "2021-04-03T10:15:00Z"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "HH:mm"
if let date1 = formatter.date(from: StDate) {
let tme = dateFormatterPrint.string(from: date1)
print(tme)
}
Out Put
15:45
How to get 10:15
This most likely happens because you reside in a GMT+5 time zone. Meanwhile, your date string is UTC.
Use this to override the time zone:
dateFormatterPrint.timeZone = TimeZone(abbreviation: "UTC")
Your dateFormattedPrint by default uses your local timezone. Add
dateFormatterPrint.timeZone = TimeZone(identifier: "GMT")
to make it use GMT.
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
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/
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
This question already has answers here:
Converting UTC date format to local nsdate
(7 answers)
Closed 5 years ago.
I'm working on date formatter, I got a response of date from server in string type, which I convert into date format but what I want to do is to convert a date and then manage according to local time.
For example, if 12/06/2017, 06:48:03 is a date from server and i'm from Pakistan so it gives me a date and time according to GMT+5 which is 12/06/2017, 11:48:03
Same as from India it gives me a date and time according to GMT+5:30 which is 12/06/2017, 12:18:03
Here is a source code
public class func converServerTimeStampToDate (_ timeStamp: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy, hh:mm:ss a"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let localDate = dateFormatter.date(from: timeStamp)
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "MM/dd/yyyy, hh:mm:ss a"
// return dateFormatter.string(from: localDate!)
return dateFormatter.date(from:dateFormatter.string(from:
localDate!))!
}
Any help would be appreciated !!
If you want the result to be a Date object just use the first part of #Intellij-Shivam's answer:
func serverToLocal(date:String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let localDate = dateFormatter.date(from: date)
return localDate
}
(note that DateFormatter.date(from:) returns an optional, which is correct because the input date string might not be in the correct format.)
There is no such thing as a Date in your local time zone. Dates don't have a time zone. They record an instant in time all over the planet.
To display a date in your local time zone you can use the DateFormatter class method localizedString():
let dateString = DateFormatter.localizedString(
inputDate,
dateStyle: .medium,
timeStyle: .medium)
I hope this will work for your problem
func serverToLocal(date:String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let date = dateFormatter.date(from: date)
dateFormatter.timeZone = TimeZone.current
let timeStamp = dateFormatter.string(from: date!)
return date
}