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
}
Related
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
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 .
I am trying to get current date and time from a unix time stamp but it keeps giving me the wrong date this is the code i am currenty
func getDateFromStamp(timeInterval:Int) -> String{
let date = NSDate(timeIntervalSince1970: TimeInterval(timeInterval))
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, MMM d, h:mm a"
let dateString = dateFormatter.string(from: date as Date)
return dateString
}
Usually unix timestamps are in milliseconds, but Date uses seconds. You might need to divide your timestamp by 1000.
Possible errors:
I try to use milliseconds instead of seconds. timeIntervalSince1970: TimeInterval uses seconds. Divide timeInterval by 1000 beforehand.
Or you have not setup TimeZone.
Don't forget to use Date() instead of NSDate()
It depends on your results and input parameters.
EDIT
To change time zone use this code:
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+01:00")
For Swift 4:
Step:-1 Convert to Date:
let timestamp = "Your TimeStamp here"
var dateFromTimeStamp = Date(timeIntervalSince1970: timestamp as! TimeInterval / 1000)
Step:-2 Convert to appropriate time zone:
let dateFormatter = DateFormatter();
let dateFormat = "dd MMM yyyy"; //Any TimeFormat you want
dateFormatter.dateFormat = dateFormat;
let formattedDate = dateFormatter.string(from: dateFromTimeStamp);
dateFormatter.locale = NSLocale.current;
dateFormatter.timeZone = TimeZone(abbreviation: "GMT"); //Pass Appropriate time zone here.
dateFormatter.dateFormat = dateFormat as String;
let sourceDate = dateFormatter.date(from: formattedDate as String);
print(sourceDate)
Hope so this helps You.
I am getting date string from server like that "2017-08-05T00:30:00.000+02:00". Below is my code for date formatter.
let dateFormatter: DateFormatter = DateFormatter()
let serverDateString = "2017-08-05T00:30:00.000+02:00"
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZZ"
dateFormatter.locale = Foundation.Locale(identifier: "en_US_POSIX")
let currentDate: Date = dateFormatter.date(from: serverDateString)!
But it returns 2017-08-04 22:30:00 +0000. Which is wrong. Any suggestions?
In Swift 3
You can change your server time string to UTC time Date as:
let dateFormatter: DateFormatter = DateFormatter()
var serverDateString = "2017-08-05T00:30:00.000+02:00"
let index = serverDateString.index(serverDateString.startIndex, offsetBy: 19)
serverDateString = serverDateString.substring(to: index)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = TimeZone.init(identifier: "UTC")
let currentDate: Date = dateFormatter.date(from: serverDateString)!
Your Code for parsing date is correct: 2017-08-05T00:30:00.000+02:00 and 2017-08-04 22:30:00 +0000 represent the same time, just in different time zones. Your only problem is that Date doesn't actually store the time zone
yyyy-MM-dd'T'hh:mm:ss.SSSZZZZZZ
This is correct date formate for your input string. Here is the Apple Document for more description.
Here is my code:
var strInputDateString: String = "2017-08-05T00:30:00.000+02:00"
var dateFormat = DateFormatter()
dateFormat.dateFormat = "yyyy-MM-dd'T'hh:mm:ss.SSSZZZZZZ"
//Set new dateFormate
var date1: Date? = dateFormat.date(from: strInputDateString)
dateFormat.dateFormat = "dd-MM-YYYY hh:mm:ss"
// Your Desire
var strOutputDateString: String = dateFormat.string(from: date1!)
print("\(strInputDateString)")
print("\(strOutputDateString)")
output:
Main input String:2017-08-05T00:30:00.000+02:00
Converted String: 05-08-2017 04:00:00
For now, I tried to convert your date format with my custom. It's give me the perfect output.
Actually, your code is good.
I copied your data and ran it in playground.
What kind of format you want it be?
Try this
let dateFormatter: DateFormatter = DateFormatter()
let serverDateString = "2017-08-05T00:30:00.000+02:00"
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXX"
dateFormatter.locale = Foundation.Locale(identifier: "en_US_POSIX")
let currentDate: Date = dateFormatter.date(from: serverDateString)!
Hope this helps
The step you are missing is to again use your DateFormatter to format the date into a string. When you use print on the date, it will always show GMT. For illustration purposes, I've set the TimeZone to Berlin to match the original offset of +2:00.
let dateFormatter: DateFormatter = DateFormatter()
let serverDateString = "2017-08-05T00:30:00.000+02:00"
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZZ"
// Hard set to Berlin
dateFormatter.timeZone = TimeZone(identifier: "Europe/Berlin")
let currentDate: Date = dateFormatter.date(from: serverDateString)!
// Your missing step
dateFormatter.string(from: currentDate)
Remember that DateFormatters are about:
Parsing from a String - df.date(from: String)
Formatting from a Date - df.string(from: Date)