All,
I am trying to convert UTC date to local date . Below is my code. But, even after converting I get both dates in UTC only.
static func getTodayDateInLocalTimeZone() -> Date{
let todaydateInUTC = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
let utcDateString = dateFormatter.string(from: todaydateInUTC)
print("Date::: utcDateString: \(utcDateString)")
// Changing to Current timezone
let timzoneIdentiier = TimeZone.current.identifier
let timezone = TimeZone(identifier: timzoneIdentiier)
let abbrv = timezone?.abbreviation()
let dateFormatter1 = DateFormatter()
dateFormatter1.timeZone = TimeZone(identifier: abbrv!)
dateFormatter1.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
print("Date:::timeZone: \(timzoneIdentiier) == \(String(describing: abbrv))")
let formattedDate1 = dateFormatter1.date(from: utcDateString)
print("Date:::: \(formattedDate1)")
return formattedDate1!
}
Here is what I get when I print
Date::: utcDateString: 2021-01-20T17:39:15+0000
Date:::timeZone: America/New_York == Optional("EST")
Date:::: Optional(2021-01-20 17:39:15 +0000)
Please let me know why is it now changing to the local timezone.
Thanks
First of all, a date does not have a time zone.
So let todaydateInUTC = Date() actually means let todaydate = Date().
The time zone becomes relevant, when you want to present a date to the user.
So instead of creating a new date from a the utcDateString, you just need to create another date string from the same date variable.
let formattedDate1 = dateFormatter1.date(from: utcDateString) becomes let tzDateString = dateFormatter1.string(from: todaydate).
This also means your function should return a string instead of a date.
For example:
func getTodayDateInLocalTimeZone() -> String
{
let now = Date()
// Just for debugging. Not for the result.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
let utcDateString = dateFormatter.string(from: now)
print("Date::: utcDateString: \(utcDateString)")
let tz = TimeZone.current
let dateFormatter1 = DateFormatter()
dateFormatter1.timeZone = tz
dateFormatter1.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
print("Date:::timeZone: \(tz) == \(String(describing: tz.abbreviation()))")
let tzDateString = dateFormatter1.string(from: now)
print("Date:::: \(tzDateString)")
return tzDateString
}
For me it results in:
Date::: utcDateString: 2021-01-20T18:19:44+0000
Date:::timeZone: Europe/Berlin (current) == Optional("CET")
Date:::: 2021-01-20T19:19:44+0100
Related
I am working in iOS app with Dateformatter which is return wrong time. I don't have any idea to fix this. Can anyone please correct me to get correct time?
let dateString = "2020-08-11T05:32:33.000Z"
func approach1(){
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
guard let date = dateFormatter.date(from: dateString) else {fatalError()}
printTime(date: date)
}
func approach2(){
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
guard let date = dateFormatter.date(from: dateString) else { fatalError()}
printTime(date: date)
}
func printTime(date: Date){
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
dateFormatter.amSymbol = "AM"
dateFormatter.pmSymbol = "PM"
let time = dateFormatter.string(from: date)
print("date: \(date)")
print("Time: \(time)") // Here it's always wrong time with those approach.
}
Current Result:
By default dateFormatter works with local time zone. To have correct display set its time zone to UTC : dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
There's nothing wrong. The date formatter returns the correct time
The date string
"2020-08-11T05:32:33.000Z"
represents a date in UTC(+0000).
Your local time zone is obviously UTC+0530. DateFormatter considers the local time zone by default.
To format the time also in UTC you have to set the time zone of the date formatter explicitly
func printTime(date: Date) {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(identifier: "UTC")
dateFormatter.dateFormat = "h:mm a"
dateFormatter.amSymbol = "AM"
dateFormatter.pmSymbol = "PM"
let time = dateFormatter.string(from: date)
print("date: \(date)")
print("Time: \(time)")
}
You need to specify the time zone when formatting to string (by default it's using your current local time zone):
func printTime(date: Date) {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC") // <- add here
dateFormatter.dateFormat = "h:mm a"
dateFormatter.amSymbol = "AM"
dateFormatter.pmSymbol = "PM"
let time = dateFormatter.string(from: date)
print("date: \(date)")
print("Time: \(time)")
}
I want to set "EST" as the default time zone for every user, but there is one condition that needs to be check in the current date at 7:45 PM. So I am comparing two dates, but the problem is when I convert the current Date to String it gives me the correct EST time, when I convert that String again to Date in EST it gives me time 4 hours ahead of EST. Here is the code for conversion
class func getCurrentDateTime() -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "EST")
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
let dateString = dateFormatter.string(from: Date())
print(dateString)
let convertDateFormatter = DateFormatter()
convertDateFormatter.dateFormat = "dd-MM-yyyy"
convertDateFormatter.timeZone = TimeZone(abbreviation: "EST")
let currentDate = convertDateFormatter.string(from: Date())
print(currentDate)
let comparedDateFormatter = DateFormatter()
comparedDateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
comparedDateFormatter.timeZone = TimeZone(abbreviation: "EST")
let comparedDate = comparedDateFormatter.date(from: "\(currentDate) 19:45:00")
print(comparedDate)
let currentDateFormatter = DateFormatter()
currentDateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
comparedDateFormatter.timeZone = TimeZone.init(abbreviation: "EST")
let currentDateAndTime = currentDateFormatter.date(from: dateString)
print(currentDateAndTime)
return dateString
}
So a date does not have a time zone.
So when I use a dateFormatter to convert a date to a string representation of the string will reflect the time zone the dateFormatter is set to.
But when you use the same formatter to convert the the string back into a date the date would not have the the time zone offset anymore.
So this sounds to me as if it is working properly.
Edit:
So if you are trying to compare two dates I would do something like:
let date1 = Date()
let date2 = Date().addingTimeInterval(100)
if date1 == date2 {
// dates are exactly equal
} else if date1 > date2 {
// date1 is the most recent
} else if date1 < date2 {
// date2 is the most recent
}
And if I were trying to display these dates I would use the date formatter to convert them to strings.
I modified the code as you requested:
func getCurrentDateTime() -> String {
var checkString : String!
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "EST")
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss a"
let dateString:String! = dateFormatter.string(from: Date())
let dateFormatter1 = DateFormatter()
dateFormatter1.timeZone = TimeZone(abbreviation: "EST")
dateFormatter1.dateFormat = "dd-MM-yyyy HH:mm:ss"
let dateString1:String! = dateFormatter1.string(from: Date())
let convertDateFormatter = DateFormatter()
convertDateFormatter.dateFormat = "dd-MM-yyyy"
convertDateFormatter.timeZone = TimeZone(abbreviation: "EST")
let currentDateformat = convertDateFormatter.string(from: Date())
let compareDate = "\(currentDateformat) 07:45:00 PM"
let compareDate1 = "\(currentDateformat) 07:45:00"
if dateString == compareDate {
checkString = "equal date"
}
if dateString1 < compareDate1{
checkString = "greater than"
} else {
checkString = "less than"
}
return checkString
}
func getCurrentDateTime() -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "EST")
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
let dateString = dateFormatter.string(from: Date())
let convertDateFormatter = DateFormatter()
convertDateFormatter.dateFormat = "dd-MM-yyyy"
convertDateFormatter.timeZone = TimeZone(abbreviation: "EST")
let currentDate = convertDateFormatter.string(from: Date())
let comparedDateFormatter = DateFormatter()
comparedDateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
let comparedDate = comparedDateFormatter.date(from: "\(currentDate) 19:45:00")
let currentDateFormatter = DateFormatter()
currentDateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
let currentDateAndTime = currentDateFormatter.date(from: dateString)
return dateString
}
Plesae check this code .
Actually I didn't find anything wrong with the code.
The Date always be in UTC timezone. The DateFormatter did the magic.
To print Date in as per the format:
use string(from:) method.
if let currentDateAndTime = currentDateFormatter.date(from: dateString) {
print(currentDateFormatter.string(from: currentDateAndTime))
}
NB: When working with fixed format dates, such as RFC 3339, you set
the dateFormat property to specify a format string. For most fixed
formats, you should also set the locale property to a POSIX locale
("en_US_POSIX"), and set the timeZone property to UTC.
Hi I want to get time as 11:40 from 2017-07-31T11:40:00.000Z
Below is the code I am using:
let formatter = Foundation.DateFormatter()
formatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss.sssZ" //2017-04-01T18:05:00.000
let date1 = formatter.date(from: data.arvTime)
print("date:\(String(describing: date1))")
let dateFormatterPrint = Foundation.DateFormatter()
dateFormatterPrint.dateFormat = "HH:mm"
let resultTime = dateFormatterPrint.string(from: date1!)
print("time:\(String(describing: resultTime))")
Getting time as 1:29 i.e. I am getting wrong time.
Please help me to solve this issue.
use the dateformat
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
instead of
formatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss.sssZ"
for full code
let formatter = Foundation.DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" //2017-04-01T18:05:00.000
let date1 = formatter.date(from: "2017-04-01T18:05:00.000Z")
print("date:\(String(describing: date1))")
formatter.dateFormat = "HH:mm"
let resultTime = formatter.string(from: date1!)
print("time:\(String(describing: resultTime))")
option-2
let formatter = Foundation.DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.sssZ" //2017-04-01T18:05:00.000
let date1 = formatter.date(from: "2017-04-01T18:05:00.000Z")
print("date:\(String(describing: date1))")
formatter.timeZone = TimeZone(abbreviation: "UTC")
formatter.dateFormat = "HH:mm"
let resultTime = formatter.string(from: date1!)
print("time:\(String(describing: resultTime))")
output
NSLog always prints the date object in GMT timezone, not your local timezone. use your local time zone
Try this
Use the timeZone property of the dateFormatter.
let formatter = Foundation.DateFormatter()
formatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss.sssZ"
let date1 = formatter.date(from: "2017-07-31T11:40:00.000Z")
print("date:\(String(describing: date1))")
let dateFormatterPrint = Foundation.DateFormatter()
dateFormatterPrint.timeZone = TimeZone(abbreviation: "UTC")
dateFormatterPrint.dateFormat = "HH:mm"
let resultTime = dateFormatterPrint.string(from: date1!)
print("time:\(String(describing: resultTime))")
For kotlin create Extension you can check it out
The first Step convert the String to local Date here dateFormat is Your input data formate and timeZone is input Time Zoon
fun String.toDate(dateFormat: String = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'", timeZone: TimeZone = TimeZone.getTimeZone("UST")): Date? {
val parser = SimpleDateFormat(dateFormat, Locale.getDefault())
parser.timeZone = timeZone
return parser.parse(this)}
Secon Step is to convert local time into time formate you want like : 2022 23 12 10:50:05
fun Date.formatTo(dateFormat: String, timeZone: TimeZone = TimeZone.getDefault()): String {
val formatter = SimpleDateFormat(dateFormat, Locale.getDefault())
formatter.timeZone = timeZone
return formatter.format(this)}
Simple call these functions like this
fun String.convertToLocalTime():String{
val localFormat="dd-MM-yyyy HH:mm:ss"
this.toDate()?.formatTo(dateFormat = localFormat)?.let {
return it
}
return ""}
if I choose date like let dateString = "2014-01-12", How would I convert string to
dateFormatter.dateFormat = "yyyy-MM-dd"
and then in below format
dateFormatter.dateFormat = "dd-MM-yyyy"
I get nil values in Xcode 8 in Swift 3.0
{
let dateString = "2014-01-12"
dateFormatter.locale = Locale(identifier:"ja_JP")
dateFormatter.dateFormat = "dd-MM-yyyy"
print(dateFormatter.date(from:dateString))
}
or
let dateString = "2014-01-12"
dateFormatter.dateFormat = "yyyy-MM-dd"
var s = dateFormatter.date(from: dateString)! as Date
dateFormatter.dateFormat = "dd-MM-yyyy"
s = dateFormatter.date(from: dateString)! as Date
print("SecondDate\(s)")
In Xcode 7 it works fine.
If you want to convert to date formate yyyy-MM-dd to dd-MM-yyyy then your last line should be.
let dateString = "2014-01-12"
dateFormatter.dateFormat = "yyyy-MM-dd"
var s = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = "dd-MM-yyyy"
Get formatted date like this
let dateStr = dateFormatter.string(from: s)
Instead of
s = dateFormatter.date(from: dateString)! as Date
You need to just change format of DateFormatter and get it as the String.
Need to change date string into "date string" as Date then you can change into your particular format. For every format you need to do this first.
You can use the code below.
Swift 3
extension String {
func changeDate(_ mydate:String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = DateFormatter.Style.long
dateFormatter.dateFormat = "yyyy-MM-dd"
let convertedDate = dateFormatter.date(from: mydate)
dateFormatter.dateFormat = "dd-MM-yyyy"
let date = dateFormatter.string(from: convertedDate!)
return date
}
}
You can use this
let dateString = "2014-01-12"
let dateFormatterNew = DateFormatter()
dateFormatterNew.dateFormat = "yyyy-MM-dd"
let date = dateFormatterNew.date(from: dateString)! as Date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let dateNew = dateFormatter.string(from: date )
print(dateNew)
do it like this
let datestring = "2014-01-12"
let dateF = NSDateFormatter()
dateF.dateFormat = "yyyy-MM-dd"
let firstDate = dateF.dateFromString(datestring)
dateF.dateFormat = "dd-MM-yyyy"
let newDateString = dateF.stringFromDate(firstDate!)
print("NEW DATE FORMAT IS : \(newDateString)")
I have a date string in this format:
2016-06-20T13:01:46.457+02:00
and I need to change it to something like this:
20/06/2016
Previously I have always used this library -> SwiftDate to manipulate the dates, but it doesn't work now.
I tried also something like:
let myDate = self.dateNoteDict[indexPath.row]!
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"
let date = dateFormatter.dateFromString(myDate)
print("date -> \(date)")
but it doesn't work. How can I do?
Thanks in advance.
The standard ISO8601 date format with fractional seconds and time zone is
yyyy-MM-dd'T'HH:mm:ss.SSSZ
let myDate = "2016-06-20T13:01:46.457+02:00"
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") // edited
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.dateFromString(myDate)!
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.stringFromDate(date)
Swift 3:
let myDate = "2016-06-20T13:01:46.457+02:00"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // edited
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from:myDate)!
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:date)
In macOS 10.13+, iOS 11+ ISO8601DateFormatter is an alternative as input formatter
let myDate = "2016-06-20T13:01:46.457+02:00"
let inputFormatter = ISO8601DateFormatter()
inputFormatter.formatOptions = [.withFullDate, .withFullTime, .withFractionalSeconds]
let date = dateFormatter.date(from:myDate)!
let outputFormatter = DateFormatter()
outputFormatter.locale = Locale(identifier: "en_US_POSIX")
outputFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:date)
I always use this code while converting String to Date .
(Swift 3)
extension String
{
func toDate( dateFormat format : String) -> Date
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
if let date = dateFormatter.date(from: self)
{
return date
}
print("Invalid arguments ! Returning Current Date . ")
return Date()
}
}
and just call like . .
print ( "2016-06-20T13:01:46.457+02:00".toDate(dateFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSZ") )
//Capital HH for 24-Hour Time
I always use this code while converting String to Date. (Swift 4.2)
let myDate = datePicker.date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = myDate
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:date)
print(dateString)
You can try manually also:
let myDate = "2019-02-22T08:21:11+0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = myDate
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:date)
print(dateString)