DateFormatter showing different date - ios

I am new to iOS and I want to add some milliseconds say (5) to my date. I have used the below code but I am not getting the exact date which I am using
let str_TimeStamp = "2017-08-09 10:26:30.8"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.S"
formatter.timeZone = NSTimeZone(abbreviation: "UTC")! as TimeZone
var dateInput: Date? = formatter.date(from: str_TimeStamp)
dateInput = dateInput?.addingTimeInterval(TimeInterval(5*100))
let endtime = formatter.string(from: dateInput!)
print(endtime)
I am getting the output having some delay of mins
2017-08-09 10:28:10.8

The parameter of the addingTimeInterval is the value to add, in
seconds.
So, addingTimeInterval(TimeInterval(5*100)) - adds 500 seconds = 8 minutes.
If you want to add some milliseconds say (5), you should add this time interval: 0.005
So, the final code is:
let str_TimeStamp = "2017-08-09 10:26:30.8"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSSS"
formatter.timeZone = TimeZone(abbreviation: "UTC")
var dateInput = formatter.date(from: str_TimeStamp)
dateInput = dateInput?.addingTimeInterval(5/1000)
if let dateInput = dateInput {
let endtime = formatter.string(from: dateInput)
print(endtime) // prints 2017-08-09 10:26:30.8050
}

Related

why i get an error in the date formatter code?

I’m trying to convert my AM PM time pickers to 24h format to print the start and end time to calculate the price but i got an unknown error. attached is photo of my UI to simplify the idea and my code.
Note: the end time is automatically shows after i choose the start time
#objc func donePressed(){
// formatter
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
startTimeTxt.text = formatter.string(from: StartTimePicker.date)
self.view.endEditing(true)
endTimeTxt.text = formatter.string(from: EndTimePicker.date)
self.view.endEditing(true)
let starttimecal = StartTimeTxt.text!
let endtimecal = EndTimeTxt.text!
let StartTo24 = starttimecal
let EndTo24 = endtimecal
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
let sTime = dateFormatter.date(from: startTo24)
dateFormatter.dateFormat = "HH:mm"
let sTime24 = dateFormatter.string(from: sTime!)
print("24 hour formatted Date:", sTime24)
let eTime = dateFormatter.date(from: endTo24)
dateFormatter.dateFormat = "HH:mm"
let eTime24 = dateFormatter.string(from: eTime!) // here the fatal error comes after i choose the start time from simulator
print("24 hour formatted Date:", eTime24)
}
To get the 12h time format to display in the text fields you can use the formatter you already have but I also like to set the locale
let dateFormatter12h = DateFormatter()
dateFormatter12h.locale = Locale(identifier: "en_US_POSIX")
dateFormatter12h.dateFormat = "h:mm a"
To calculate the time difference there is a function for that in the Calendar class, here we calculate the number of hours and minutes between two dates (this is an assumption since I don't know exactly what calculation you want to do)
let hourAndMinutes = Calendar.current.dateComponents([.hour, .minute], from: startDate, to: endDate)
Below is a more complete example
//Sample data
let startDate = Date()
let endDate = startDate.addingTimeInterval(3.25*60*60) //add 3h and 15 minutes
// Format and print in 12h format
let dateFormatter12h = DateFormatter()
dateFormatter12h.locale = Locale(identifier: "en_US_POSIX")
dateFormatter12h.dateFormat = "h:mm a"
let start = dateFormatter12h.string(from: startDate)
let end = dateFormatter12h.string(from: endDate)
print(start, end)
// Calculate time difference in hours and minutes
let hourAndMinutes = Calendar.current.dateComponents([.hour, .minute], from: startDate, to: endDate)
print(hourAndMinutes)
// Calculate price, the formula is just an example
let price = hourAndMinutes.hour! * 15 + hourAndMinutes.minute! * 15 / 60
print(price)
Output
6:46 PM 10:01 PM
hour: 3 minute: 15 isLeapMonth: false
48

Convert UTC date to local date swift4

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

Date from String is not giving correct date

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.

Ios Swift Date Convert from TimeZone

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "KST")
let nowstring = dateFormatter.string(from: Date())
let nowdate = dateFormatter.date(from: nowstring)
print(nowstring)
print(nowdate)
print this 2018-07-24T15:06:26
Optional(2018-07-24 06:06:26 +0000)
i want nowdate value 2018-07-24T15:06:26
but String to Date without timezone
I have to use to timeIntervalSince so nowdate is must have timezone
let today = NSDate()
print("\(today)")
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let nowDatestring = formatter.string(from: today)
formatter.timeZone = TimeZone(abbreviation: "KST")
let kstDate = formatter.date(from: nowDatestring)
print("\(kstDate!)")
formatter.timeZone = TimeZone(abbreviation: "PST")
let pstDate = formatter.date(from: nowDatestring)
print("\(pstDate!)")
formatter.timeZone = TimeZone(abbreviation: "IST")
let istDate = formatter.date(from: nowDatestring)
print("\(istDate!)")
Date is a specific point in time, which is independent of time zone. If you print a date value it will be always independent of any calendar or time zone. It will give same value for you(KST) and me(IST). You can specify your time zone when you format it using DateFormatter.

How to get time from YYYY-MM-dd'T'HH:mm:ss.sssZ

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 ""}

Resources