How to convert string Date to in milliseconds swift 3 - ios

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

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

Date Time change when convert to string issue

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)

Convert date string to date object

Actual string - January 31, 2020 at 11:59:59 p.m. (ET).
format - "MMMM d, yyyy 'at' hh:mm:ss aa"
Not able to convert this string to Date object. Tried various date format and but unable to change string to Date object.
Please help
You could delete the non-standard character . between p and m and escape the parentheses around the time zone
let dateString = "January 31, 2020 at 11:59:59 p.m. (ET)"
let trimmedDateString = dateString.replacingOccurrences(of: ".m.", with: "m")
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "MMMM d, yyyy 'at' hh:mm:ss a (v)"
let date = formatter.date(from: trimmedDateString)
let raw = "January 31, 2020 at 11:59:59 p.m. (ET)"
func getDateFrom(_ raw: String) -> Date? {
if let i = (raw.range(of: "(")?.lowerBound) { // get index of open parenthesis
var zone: TimeZone?
let dateString = String(raw.prefix(upTo: i)) // January 31, 2020 at 11:59:59 p.m.
let zoneString = String(raw.suffix(from: i)) // (ET)
switch zoneString { // determine time zone
case "(ET)", "(EST)", "(EDT)": // study your data source and learn how they may express time zones
zone = TimeZone(abbreviation: "EDT")
default:
return nil // failure
}
let formatter = DateFormatter()
formatter.dateFormat = "MMMM d, yyyy 'at' hh:mm:ss a"
formatter.timeZone = zone
formatter.amSymbol = "a.m."
formatter.pmSymbol = "p.m."
if let date = formatter.date(from: dateString) {
return date
} else {
return nil
}
} else {
return nil
}
}
if let date = getDateFrom(raw) {
print(date) // 2020-02-01 04:59:59 +0000
}
This should be a good starting point. There are a number of ways to do this, such as whether you want it to fail if a time zone can't be determined, how to extract the time zone (using abbreviations, identifiers, seconds from GMT), etc. I like vadian's answer if I was completely comfortable with the time zone. But time zones are so inconsistent and surprisingly non-standardized when expressed as strings, that I'd rather dedicate a mechanism to getting it and making sure it's valid.
That said, this is a relatively crude example of where I'd begin—a finished version would be more nuanced. In this example, if the time zone fails, the function fails.

Why can I not format my NSDate with the specified time zone with NSDateFormatter?

I want to get a date that is represented in a String with a time zone GMT+1 and display it on screen with the local time zone GMT+10.
I have 2 methods, one is for create a date from a String (with GMT+1 timeZone), the other one is to format the date into a String (with localTimeZone GMT+10):
func dateFromString(dateString: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT+1")
dateFormatter.dateFormat = "M/d/yyyy hh:mma"
return dateFormatter.dateFromString(dateString)
}
func stringFromDate(date: NSDate) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone.localTimeZone()
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
return dateFormatter.stringFromDate(date)
}
In the playground, when I do this:
let date = dateFromString("4/8/2015 1:29am")!
println(date)
println(stringFromDate(date))
I get the following output on the right side:
"Apr 8, 2015, 1:29 AM"
"2015-04-07 15:29:00 +0000"
"1:29 AM"
I don't understand why I don't get what I am expecting and looking for:
"Apr 8, 2015, 1:29 AM"
"2015-04-08 10:29:00 +0000"
"10:29 AM"
What's wrong?
Input formatters need the time zone in their string. Like so:
func dateFromString(dateString: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "M/d/yyyy hh:mma z"
return dateFormatter.dateFromString(dateString)
}
let date = dateFromString("4/8/2015 1:29am GMT+01")!
Also note that NSTimeZone names have a two digit offset. Compare in the playground
var oops = NSTimeZone(abbreviation: "GMT+1")
var righteous = NSTimeZone(abbreviation: "GMT+01")
The first is nil, the second is not.
I wouldn't trust the formatting of a time stamp that the debugger prints. In my experience dates are always in UTC regardless of the time zone you set according to the log. Try adding the date as a string to a label on the project and see if it's right.
The reasoning behind this as far as I know is that when you print to the log, all it's doing is calling -description. In the case of NSDate this will return in UTC by definition.

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