let dateFormater : DateFormatter = DateFormatter()
dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormater.date(from: "2016-11-11T11:42:27Z")
print("date is ---->%#",date)
let timestamp = date?.timeIntervalSince1970
print("timestamp is ---->%#",timestamp!)
let str = String(format: "%#",timestamp!)
print("str value is ---->%#",str)
date is -----> 2016-11-11 11:42:27 +000
timestamp is----->1478864547.0
str value is-----> null
Getting date and time stamp value. How to change timestamp value into string. Means 1478864547.0(timestampvalue) to string formate
let str = String(format: "%#",timestamp!) whats wrong this line.
You can simply use let timestampInString = "\(timestamp)".
If it is optional then
if let timestamp = date?.timeIntervalSince1970 {
let timestampInString = "\(timestamp)"
}
The problem is that timestamp is not an object - it's a TimeInterval (which is just a typealias for Double). If you want to use a formatted string, you need to do "%lf".
You are getting null value. timestamp is not a String value so you can no get a String value directly, You have to use Float to String Casting
Do as follow I am sure it will work for you.
let dateFormater : DateFormatter = DateFormatter()
dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormater.date(from: "2016-11-11T11:42:27Z")
print("date is ---->%#",date)
let timestamp = date?.timeIntervalSince1970
print("timestamp is ---->%#",timestamp!)
let str = String(format: "%0.0f",timestamp!)
print("str value is ---->%#",str)
TimeInterval is typealias for Double, So use or " 0.0f " " %lf ".
Related
I bet this is simple. I'm trying in Xcode playgrounds to play with getting a string date
let string = "2022-11-27 00:00:00 +0000"
and converting that into a Date object that's formatted like DD-MM-YYYY
func airdateFormat(_ key: String) -> Date? {
let expectedFormat = Date().formatted(.dateTime.day().month(.wide).year())
let date = try! Date(strategy: expectedFormat)
return date
}
I also tried
func airdateFormat(_ key: String) -> Date? {
guard let dateString = self[key] as? String else { return nil }
let dateFormatted = DateFormatter.dateFormat(fromTemplate: "MM-DD-YYYY", options: Int, locale: Locale?)
return dateFormatted().date(from: dateString)
}
}
I'm parsing this Date string from json hence the guard/else statement
You need to use a format that matches your input to parse the string to a Date
If you want to use the DateFormatter
let string = "2022-11-27 12:34:56 +0000"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let date = formatter.date(from: string)
and for recent OS versions you use a FormatStyle
let formatStyle = Date.FormatStyle()
.year(.defaultDigits)
.month(.twoDigits)
.day(.twoDigits)
.hour()
.minute()
.second()
.timeZone()
let date = try formatStyle.parse(string)
Getting nil converting date string to date
func convertDateFormater(dateStr: ""2022-10-22T22:22:16:2216Z"") -> String? {
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let strSelected = inputFormatter.date(from: dateStr)
}
convertDateFormater(dateStr: "2022-10-23T00:00:00.000Z") // Working fine
***convertDateFormater(dateStr: ""2022-10-22T22:22:16:2216Z"") // Not Working fine getting nil***
Should work convertDateFormater(dateStr: ""2022-10-22T22:22:16:2216Z"")
There are many issues in this code
"" … "" is invalid syntax.
There is no parameter type defined.
Nothing – or even the wrong type – is returned.
Z is a format specifier, it must not be wrapped in single quotes.
Apart from that look at your date string. A colon between seconds and milliseconds is very uncommon but it works with this code
func convertDateFormater(dateStr: String) -> Date? {
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss:SSSZ"
return inputFormatter.date(from: dateStr)
}
convertDateFormater(dateStr: "2022-10-22T22:22:16:2216Z")
But you cannot convert both strings (colon and period separator) with the same date format.
To do so you need a second parameter
func convertDateFormater(dateStr: String, hasColonMillisecondSeparator: Bool = false) -> Date? {
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = hasColonMillisecondSeparator ? "yyyy-MM-dd'T'HH:mm:ss:SSSZ" : "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
return inputFormatter.date(from: dateStr)
}
convertDateFormater(dateStr: "2022-10-23T00:00:00.000Z")
convertDateFormater(dateStr: "2022-10-22T22:22:16:2216Z", hasColonMillisecondSeparator: true)
I have a string what I get from the server which looks like:
You blocked until 2022-01-01T11:00:00.350Z
And now I want to convert it to human-readable date like
2022-01-01 11:00
For this I tried to find the date first:
let types: NSTextCheckingResult.CheckingType = [.date]
if let detector = try? NSDataDetector(types: types.rawValue) {
let range = NSMakeRange(0, message.count)
let matches = detector.matches(in: message,
options: NSRegularExpression.MatchingOptions(rawValue: 0),
range: range)
if !matches.isEmpty {
for match in matches {
print(match.date)
let aSubstring = NSString(string: message).substring(with: match.range)
print(aSubstring)
}
}
}
So as a result match.date returned me 2022-01-01 11:00:00 +0000 but the result of aSubstring is until 2021-08-02T11:38:10.214Z.
So I'm curious why it includes until into the substring and how can I avoid that?
A possible solution is to extract the ISO8601 string omitting seconds, fractional seconds and the time zone with Regular Expression and then get the first 10 (date) and the last 5 characters (time)
let string = "You blocked until 2022-01-01T11:00:00.350Z"
if let range = string.range(of: "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}", options: .regularExpression) {
let trimmedString = String(string[range])
let humanReadable = "\(trimmedString.prefix(10)) \(trimmedString.suffix(5))"
print(humanReadable) // 2022-01-01 11:00
}
However there is a caveat: The date is in UTC. If you want the date to be displayed in the current time zone you have to use a date formatter (actually two)
let string = "You blocked until 2022-01-01T11:00:00.350Z"
if let range = string.range(of: "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}", options: .regularExpression) {
let trimmedString = String(string[range]) + "Z"
let inputFormatter = ISO8601DateFormatter()
if let date = inputFormatter.date(from: trimmedString) {
let outputFormatter = DateFormatter()
outputFormatter.locale = Locale(identifier: "en_US")
outputFormatter.dateFormat = "yyyy-MM-dd HH:mm"
let humanReadable = outputFormatter.string(from: date)
print(humanReadable)
}
}
if the date part is at the end of the string, then
you could try something a bit more convoluted but workable. Something like this:
struct ContentView: View {
#State var txt = ""
func humanDate(_ str: String) -> String? {
// convert the string to a date
let dateFormatter1 = DateFormatter()
dateFormatter1.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
// re-format the date to your liking
if let date = dateFormatter1.date(from: str) {
let dateFormatter2 = DateFormatter()
dateFormatter2.dateFormat = "yyyy-MM-dd HH:mm"
// dateFormatter2.dateFormat = "yyyy MMMM EEEE HHa:mm" // even more human readable
return dateFormatter2.string(from: date)
} else {
return nil
}
}
var body: some View {
Text(txt).onAppear {
let inputString = "You blocked until 2022-01-01T11:00:00.350Z"
if let dateStr = inputString.split(separator: " ").last {
if let theDate = humanDate(String(dateStr)) {
print("\n----> " + theDate + "\n")
txt = theDate
}
}
}
}
}
I try to convert the Date to a string and then trim it. Somehow Xcode doesnt accept beforeConvas a String. I am clueless, also tried other methods to convert the date to a string, like formatter.sring(from: date) which did not work.
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let date = Date()
let beforeConv = "\(date)"
let start = beforeConv(beforeConv.startIndex, offsetBy: 11) // Cannot call value of non-function type 'String'
let end = beforeConv(beforeConv.endIndex, offsetBy: -12) // Cannot call value of non-function type 'String'
let range = start..<end
let cleanTime = beforeConv[range]
let postZone = String(cleanTime)
It's pretty hacky (and needless) to convert a Date to a String in order to extract the day component. Luckily, Swift offers a DateComponents to do work with components that comprise a date. Here's how it works:
let date = Date()
let dateParts = Calendar.current.dateComponents([.day, .month], from: date)
let day = dateParts.day // this is an optional Int?
let month = dateParts.month
For a single component, you can also do:
// this is Int
let day = Calendar.current.component(.day, from: date)
I am parsing json using Swifty json. Now i have a key as "create_date" which can have a timestamp & as well as a date string like "2017-08-17 20:00:00".Now i am not sure when it will be a string date or it is a timestamp.I am using below code to parse this
if let timeInterval = dic?["created_at"].doubleValue {
print("timeinterval is \(timeInterval)")
date1 = NSDate(timeIntervalSince1970: (timeInterval / 1000))
date = self.getStrDateFromDate(dob: date1!) as String
}
if use dict["create_date"].doubleValue so if it a string date then it r return me 2017 & in case of timestamp it return some timestamp as 15383673563465 .
Now how do i identify if is a date or a timestamp ?
Use optional binding and cast down the value to Double with the double property of SwiftyJSON. If the downcast succeeds create the string from the Date otherwise use the date string directly.
let dateString : String
if let timeInterval = dic?["created_at"].double {
print("timeinterval is \(timeInterval)")
date1 = Date(timeIntervalSince1970: timeInterval / 1000)
dateString = self.getStrDateFromDate(dob: date1!) as String
} else {
dateString = dic?["created_at"].stringValue
}
Side note:
Why do you (bridge) cast a result to string (from getStrDateFromDate) which is supposed to be a string?
I would try a DateFormatter with the format of your possible date string, then try to convert it to a double. Or vise-versa. The order really doesn't matter too much, although it may be slightly less expensive to check for the double first.
import Foundation
func convertDate(dateString:String) -> Date? {
// try `Double`
if let timestamp = Double(dateString) {
return Date(timeIntervalSince1970: timestamp)
}
// try `DateFormatter`
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let date = formatter.date(from: dateString) {
return date
}
// give up
return nil
}
let dateString1 = String(Date().timeIntervalSince1970)
let dateString2 = "2017-08-17 20:00:00"
let dateString3 = "something"
print(convertDate(dateString: dateString1) ?? "unknown")
print(convertDate(dateString: dateString2) ?? "unknown")
print(convertDate(dateString: dateString3) ?? "unknown")
// 2017-08-17 15:15:27 +0000
// 2017-08-18 00:00:00 +0000
// unknown
Note that the default description for a Date uses GMT. In my case it's off by 4 hours, which is why the displayed time is 4 hours different from I entered.