Date Time change when convert to string issue - ios

I'm trying to subtract minute from my date. BaseDate is my date and dateMinusMin is subtract is minuteFrom my date which work completely fine.
let baseDate = "2020-03-06 06:00" //My date With format "yyyy-MM-dd HH:mm"
let dateMinusMin = Calendar.current.date(byAdding: .minute, value: -(240), to: baseDate)!
print(dateMinus4Hours) \\2020-03-06 02:00:00 +0000
But when I convert Date to string time is change dramatically and showing 07:30 instead of 02:00.
let modifyStr = Utill.getLocalStringFromDate("yyyy-MM-dd HH:mm Z", date: dateMinus4Hours, iden: "en_US_POSIX")
print(modifyStr) \\ 2020-03-06 07:30 +0530
OutPut = 2020-03-06 07:30 +0530
Function to convert Date To string
func getLocalStringFromDate(_ currentFormat:String,date:Date,iden:String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = currentFormat
formatter.locale = Locale(identifier: iden)
return formatter.string(from: date)
}

I don't find any issue in your code. you can see result in below image.
Given Input - 06:00 hours
Output - 02:00 hours (4 hours minus as you want)

Related

Get only time from Date

How to get only time from the date with am/pm. Below is my code what I have tried so far:
func changeFormat(str:String) -> String {
let dateFormatter = DateFormatter()
let newDateFormatter = DateFormatter()
// step 1
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm aa" // input format
newDateFormatter.dateFormat = "HH:mm aa" // output format
let date = dateFormatter.date(from: str)!
// step 2
let string = newDateFormatter.string(from: date)
return string
}
Usage:
let strTimeFromDate = changeFormat(str: self.response?.Data[indexPath.row].ADateTime ?? "")
input date:
06/22/2021 2:00 PM
output:
12:45 PM
Getting wrong time return after formatting. Please guide what's wrong with above code
As mentioned by #JoakimDanielson in the comment, you are mixing HH (24 hours format) with hh (12 hours format). Using hh for the dateFormatter (given your input has 02:00 PM) should fix your issue (as long as this input value was captured in the same time zone in which you intend to convert).
In case you are still seeing that the output is not expected, then it is the issue with missing timeZone info in your input. You are trying to convert String > Date > String without specifying an input timeZone & output timeZone. You can try printing these values in your implementation.
print("dateFormatter.timeZone.secondsFromGMT() : \(dateFormatter.timeZone.secondsFromGMT())")
let date = dateFormatter.date(from: str)!
print("parsed date : \(date)")
print("\n ------------------------ \n")
// step 2
print("newDateFormatter.timeZone.secondsFromGMT() : \(newDateFormatter.timeZone.secondsFromGMT())")
let string = newDateFormatter.string(from: date)
print("parsed string : \(string)")
For me it prints following. 19800 / (60 * 60) = 5.5 (+05:30)
dateFormatter.timeZone.secondsFromGMT() : 19800
parsed date : 2021-06-22 06:30:00 +0000
------------------------
newDateFormatter.timeZone.secondsFromGMT() : 19800
parsed string : 12:00 PM
The issue is - for these two conversions to happen correctly - you must specify an appropriate time zone.
String to Date
Date to String
Here's what that implementation could look like. Assuming input is "06/22/2021 2:00 PM +0530"
func changeFormat(str: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(secondsFromGMT: Int(5.5*60*60)) // +05:30
let newDateFormatter = DateFormatter()
newDateFormatter.timeZone = TimeZone(secondsFromGMT: Int(5.5*60*60)) // +05:30
dateFormatter.dateFormat = "MM/dd/yyyy hh:mm aa Z"
newDateFormatter.dateFormat = "hh:mm aa"
let date = dateFormatter.date(from: str)!
let string = newDateFormatter.string(from: date)
return string
}
When you are consuming this date string from your backend server, you should consider using appropriate time zone for it. An example, assuming input is "06/22/2021 2:00 PM +0000" -
func changeFormat(str: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) // Server timeZone (UTC)
let newDateFormatter = DateFormatter()
newDateFormatter.timeZone = TimeZone.current // User's timeZone
dateFormatter.dateFormat = "MM/dd/yyyy hh:mm aa Z"
newDateFormatter.dateFormat = "hh:mm aa"
let date = dateFormatter.date(from: str)!
let string = newDateFormatter.string(from: date)
return string
}
"HH" is for 24h format and "aa" is for 12h format so you can't mix them, so you should use "hh:mm a" instead for both DateTimeFormatter's

Get the format of date | Swift | iOS

As per the requirement, my API might return date in either "2018-01-01" or "01-01-2018" or "2018-01-01T00:00:00" format
How can I check the format of the date?
eg: my code for API response "2018-01-01" should return me "yyyy-MM-dd" etc..
I can do this by checking length of my characters and by assigning date format accordingly..but i feel this is not the right approach.
You just need to define your date formats and try each of them. One of them will succeed. Just make sure all your date strings are from the same timezone (I suppose they are all UTC) and don't forget to set the date formatter locale to "en_US_POSIX" when working with fixed format dates:
let dateStrings = ["2018-01-01", "01-01-2018", "2018-01-01T00:00:00"]
let dateFormats = ["yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd", "MM-dd-yyyy"]
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
var dates: [Date] = []
for dateString in dateStrings {
for dateFormat in dateFormats {
formatter.dateFormat = dateFormat
if let date = formatter.date(from: dateString) {
dates.append(date)
print("dateFormat:", dateFormat)
print("date:", date)
break
}
}
}
This will print
dateFormat: yyyy-MM-dd
date: 2018-01-01 00:00:00 +0000
dateFormat: MM-dd-yyyy
date: 2018-01-01 00:00:00 +0000
dateFormat: yyyy-MM-dd'T'HH:mm:ss
date: 2018-01-01 00:00:00 +0000
It's risky to have ambiguous date formats in an API. But if you are stuck with this you could make multiple DateFormatters and configure each for a specific format (by setting their dateFormat accordingly) and attempt to convert the string using each of these in turn. Once you have a success, you know which format you got (it's dateFormat).

How to convert string Date to in milliseconds swift 3

I am getting date in this format "Thu Jul 20 06:44:40 +0000 2017" and I want to convert it in milliseconds so that I can compare this milliseconds to current date milliseconds.
I want to get 20 min difference from this date "Thu Jul 20 06:44:40 +0000 2017" to current date.
I want to check If 20 or less than 20 min difference is there then only I will do other operation.
I don't know how can I check 20 min difference.
//MiliSeconds from Date
func miliSecFromDate(date : String) -> String {
let strTime = date
let formatter = DateFormatter()
formatter.dateFormat = "E MMM d HH:mm:ss Z yyyy"
let ObjDate = formatter.date(from: strTime)
return (String(describing: ObjDate!.millisecondsSince1970))
}
Your date formatter is wrong.
Try using this:
let formatter = DateFormatter()
formatter.dateFormat = "E MMM d HH:mm:ss Z yyyy"
However you SHOULDN'T be comparing dates "in milliseconds".
The reason is that, when you convert it the time zone information is lost.
You should just compare Date instances directly since Swift supports it.
Check this answer to know how:
Swift 3 - Comparing Date objects
For compare to current time time less than or equal 20
Step 1:
Make Function which convert Given time to milli second Since Current Date and time.
func miliSecFromDate(date : String) -> TimeInterval {
let strTime = date
let formatter = DateFormatter()
formatter.dateFormat = "EEE MMM dd hh:mm:ss +zzzz yyyy"
let ObjDate = formatter.date(from: strTime)
return (ObjDate?.timeIntervalSinceNow)!
}
Step 2:
Now check Given time is less than or equal to 20 minute.
if miliSecFromDate(date: "Thu Jul 20 10:42:14 +0000 2017") >= -1200 {
print("less than 20 minute")
}else{
print("condition False")
}
Try this code:
func getMilliseconds(){
let strDate = "Thu Jul 20 06:44:40 +0000 2017"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE MMM DD hh:mm:ss +zzzz yyyy"
let date = dateFormatter.date(from: strDate)
print(date!)
let millieseconds = self.getDiffernce(toTime: date!)
print(millieseconds)
}
func getDiffernce(toTime:Date) -> Int{
let elapsed = NSDate().timeIntervalSince(toTime)
return Int(elapsed * 1000)
}

GMT date string getting converted to UTC Date

**
GET GMT DATE STRING
**
func getGMTString(dateAsDate:NSDate) -> String
{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss zzz"//this your string date format
// dateFormatter.locale = NSLocale.currentLocale()
// dateFormatter.timeZone = NSTimeZone(name: "GMT")
let date = dateFormatter.stringFromDate(dateAsDate)
return date
}
OUTPUT
startDate---2016-06-29 00:00:00 GMT+5:30
endDate----2016-06-30 03:57:39 GMT+5:30
NOW TRYING to get GMT Date object from output string
func getGMTDate(string:String) -> NSDate {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss zzz"//this your string date format
// dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")!
// dateFormatter.locale = NSLocale.currentLocale()
let date = dateFormatter.dateFromString(string)
return date!
}
PROBLEM: OUTPUT DATE OBJECT MESS
startDateOBJECT---2016-06-28 18:30:00 +0000 endDateOBJECT----2016-06-30 17:30:00 +0000
Unable to figure what is going wrong
I don't understand your step 3. I looks like you're using NSLog or a Swift print to display the resulting date. That is ALWAYS done in UTC.
If you want to view your date in a different format, or with your local time zone, you need a second date formatter to convert the NSDate to an output date string.
Here's the flow:
input date string -> input date formatter -> NSDate
NSDate -> output date formatter -> display date in local time zone

How to extract day, month and year (dd-MM-yyyy) from Date (2018-09-28 09:42:00 +0000 ) without time in Date format - iOS swift?

I want to get 2018-09-28 from 2018-09-28 09:42:00 +0000 in Date format. I
can extract the same in string format but I want to get this in Date format. Here is my sample code.
let date = Date(timeIntervalSince1970: (TimeInterval(timer/1000)))
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd"
let myDate = df.string(from: date)
let updateDate = df.date(from: myDate)
//date - 2018-09-28
//updateDate - 2018-09-28 09:42:00 +0000
You can simply get your date string prefix 11 and insert noon time when parsing your string:
let str = "2018-09-28 09:42:00 +0000"
let df = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "yyyy-MM-dd HH:mm"
if let date = df.date(from: str.prefix(11) + "12:00") {
print(date.description(with: .current))
}
// Friday, September 28, 2018 at 12:00:00 PM Brasilia Standard Time

Resources