I have an array, calendarFromDateArr that is as follows:
["2017-10-30T07:41:00", "2017-10-30T11:23:00", "2017-10-30T11:48:00", "2017-11-10T00:00:00", "2017-11-13T19:43:00", "2017-12-01T00:00:00", "2017-12-31T00:00:00"]
I am using this code but dateObjects are nil.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let dateObjects = self.calendarFromDateArr2.flatMap { dateFormatter.date(from: $0) }
print(dateObjects)
var dateObjects = [Date]()
let dateFormatter = DateFormatter()
for date in self.calendarFromDateArr2 {
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let dateObject = dateFormatter.date(from: date)
dateObjects.append(dateObject!)
print(dateObjects)
}
I am using this code also but data is nil.
Because you're dateFormat string is wrong, you don't have a zone in your date strings (the Z stands for the time zone: http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns)
This example here works perfectly fine:
let dates = ["2017-10-30T07:41:00", "2017-10-30T11:23:00", "2017-10-30T11:48:00", "2017-11-10T00:00:00", "2017-11-13T19:43:00", "2017-12-01T00:00:00", "2017-12-31T00:00:00"]
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let dateObjects = dates.flatMap { dateFormatter.date(from: $0) }
print(dateObjects)
Output:
[2017-10-30 07:41:00 +0000, 2017-10-30 11:23:00 +0000, 2017-10-30 11:48:00 +0000, 2017-11-10 00:00:00 +0000, 2017-11-13 19:43:00 +0000, 2017-12-01 00:00:00 +0000, 2017-12-31 00:00:00 +0000]
Related
I am trying to make a class "Activity" as hashable for use in swiftUI List. I followed protocol instructions for making it hashable, but when I do,I get an error later in the code that says I am using an undeclared type. This type is valid (in firebase import) if I do not try to make the class hashable. I am running XCode 11.3.1 and Swift 5.
I was hoping someone could lend an eye and help me figure this out.
The updates to the code I use to make it hashable is below:
class Activity: Identifiable, Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
static func == (lhs: Activity, rhs: Activity) -> Bool {
return lhs.id == rhs.id
}
But when I do this, I get the following error later in the code which appears completely unrelated.
init(document: DocumentSnapshot) {
self.id = document.documentID
---> Use of undeclared type 'DocumentSnapshot'
When I do not add that code, I do not get that error. Clearly I am doing something stupid.
Here is the entire class (before hashable) with no errors:
import Foundation
import Firebase
class Activity: Identifiable {
var id: String?
var activityDateTime: Date
var activityName: String
var activityType: String
var displayName: String
var distance: Double
var distanceUnits: String
var duration: Double
var email: String
var teamName: String
var teamUid: String
var uid: String
init() {
self.id = nil
self.activityDateTime = Date()
self.activityName = ""
self.activityType = ""
self.displayName = ""
self.distance = 0.0
self.distanceUnits = ""
self.duration = 0.0
self.email = ""
self.teamName = ""
self.teamUid = ""
self.uid = ""
}
init(id: String, activityName: String, distance: Double) {
self.id = id
self.activityDateTime = Date()
self.activityName = activityName
self.activityType = ""
self.displayName = ""
self.distance = distance
self.distanceUnits = "Miles"
self.duration = 0.0
self.email = ""
self.teamName = ""
self.teamUid = ""
self.uid = ""
}
init(document: DocumentSnapshot) {
self.id = document.documentID
let timestamp = document.get("activityDateTime") as! Timestamp
self.activityDateTime = timestamp.dateValue()
self.activityName = document.get("activityName") as? String ?? ""
self.activityType = document.get("activityType") as? String ?? ""
self.displayName = document.get("displayName") as? String ?? ""
self.distance = document.get("distance") as? Double ?? 0.0
self.distanceUnits = document.get("distanceUnits") as? String ?? "Miles"
self.duration = document.get("duration") as? Double ?? 0.0
self.email = document.get("email") as? String ?? ""
self.teamName = document.get("teamName") as? String ?? ""
self.teamUid = document.get("teamUid") as? String ?? ""
self.uid = document.get("uid") as? String ?? ""
}
// For JSON Output
func toAnyObject() -> Any {
return [
"id": id as Any,
"activityDateTime": activityDateTime,
"activityName": activityName,
"activityType": activityType,
"displayName": displayName,
"distance": distance,
"distanceUnits": distanceUnits,
"duration": duration,
"email": email,
"teamName": teamName,
"teamUid": teamName,
"uid": uid
]
}
}
And here is the full class with hashable that causes the error to occur
import Foundation
import Firebase
class Activity: Identifiable, Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
static func == (lhs: Activity, rhs: Activity) -> Bool {
return lhs.id == rhs.id
}
var id: String?
var activityDateTime: Date
var activityName: String
var activityType: String
var displayName: String
var distance: Double
var distanceUnits: String
var duration: Double
var email: String
var teamName: String
var teamUid: String
var uid: String
init() {
self.id = nil
self.activityDateTime = Date()
self.activityName = ""
self.activityType = ""
self.displayName = ""
self.distance = 0.0
self.distanceUnits = ""
self.duration = 0.0
self.email = ""
self.teamName = ""
self.teamUid = ""
self.uid = ""
}
init(id: String, activityName: String, distance: Double) {
self.id = id
self.activityDateTime = Date()
self.activityName = activityName
self.activityType = ""
self.displayName = ""
self.distance = distance
self.distanceUnits = "Miles"
self.duration = 0.0
self.email = ""
self.teamName = ""
self.teamUid = ""
self.uid = ""
}
init(document: DocumentSnapshot) {
self.id = document.documentID
let timestamp = document.get("activityDateTime") as! Timestamp
self.activityDateTime = timestamp.dateValue()
self.activityName = document.get("activityName") as? String ?? ""
self.activityType = document.get("activityType") as? String ?? ""
self.displayName = document.get("displayName") as? String ?? ""
self.distance = document.get("distance") as? Double ?? 0.0
self.distanceUnits = document.get("distanceUnits") as? String ?? "Miles"
self.duration = document.get("duration") as? Double ?? 0.0
self.email = document.get("email") as? String ?? ""
self.teamName = document.get("teamName") as? String ?? ""
self.teamUid = document.get("teamUid") as? String ?? ""
self.uid = document.get("uid") as? String ?? ""
}
// For JSON Output
func toAnyObject() -> Any {
return [
"id": id as Any,
"activityDateTime": activityDateTime,
"activityName": activityName,
"activityType": activityType,
"displayName": displayName,
"distance": distance,
"distanceUnits": distanceUnits,
"duration": duration,
"email": email,
"teamName": teamName,
"teamUid": teamName,
"uid": uid
]
}
}
I am trying to get something similar to facebook post date/time. Like 1 min, 1 hour, Yesterday, Week ago etc.
This is the is function I am using to get this format: (Oct-22 17:28 PM)
func convertTime(serverTime: Double) -> String {
let serverTime = serverTime
let date = Date(timeIntervalSince1970: serverTime)
let dateFomatter = DateFormatter()
dateFomatter.dateFormat = "MMM-dd HH:mm a"
let strDate = dateFomatter.string(from: date)
print("This is the post's date: \(strDate)")
return strDate
}
try this code
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let before = dateFormatter.date(from: "2017-10-23 10:28:17")!
//getting the current time
let now = Date()
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.zeroFormattingBehavior = .dropAll
formatter.maximumUnitCount = 1
formatter.allowedUnits = [.year, .month, .weekOfMonth, .day, .hour, .minute]
formatter.includesApproximationPhrase = true
let formatString = NSLocalizedString("%# ago", comment: "e.g. '2 hours ago'")
let timeString = formatter.string(from: before, to: now)
How to set the first day of current week to Tuesday in Swift 3? The schedule will update every Tuesday so the first day have to start from Tuesday.
and then display on label :
thisWeekDate.text! = "\(first day of current week) - \(last day of current week)"
Full code.
let today = NSDate()
let nextTue = Calendar.current.date(byAdding: .day, value: 6, to: today as Date)
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let todayString = formatter.string(from: today as Date)
let nextString = formatter.string(from: nextTue!)
formatter.dateFormat = "dd-MMM-yyyy"
let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
let components = calendar!.components([.weekday], from: today as Date)
//Label code
thisWeekDate.text! = "\(first day of current week) - \(last day of current week)"
//If i can change the first day of current week this weekly update code can be deleted
if components.weekday == 3 {
print("Hello Tuesday")
thisWeekDate.text! = "\(todayString) - \(nextString)"
UserDefaults.standard.set(todayString, forKey: "todayStringKey")
_ = UserDefaults.standard.object(forKey: "todayStringKey") as? String
UserDefaults.standard.set(nextString, forKey: "nextStringKey")
_ = UserDefaults.standard.object(forKey: "nextStringKey") as? String
} else {
print("It's not Tuesday")
let RetrivedDate_1 = UserDefaults.standard.object(forKey: "todayStringKey") as? String
let RetrivedDate_2 = UserDefaults.standard.object(forKey: "nextStringKey") as? String
if let date_1 = RetrivedDate_1, let date_2 = RetrivedDate_2 {
thisWeekDate.text! = "\(date_1) - \(date_2)"
}
}
App Design Screenshot
Create a custom Gregorian calendar and set the first weekday to Tuesday
var customCalendar = Calendar(identifier: .gregorian)
customCalendar.firstWeekday = 3
Then you can get the week interval with
var startDate = Date()
var interval = TimeInterval()
customCalendar.dateInterval(of: .weekOfMonth, start: &startDate, interval: &interval, for: Date())
let endDate = startDate.addingTimeInterval(interval - 1)
print(startDate, endDate)
I have formatted date in string format like "07/06/2017 11:23 AM" so I want to convert it into again date format. How to do this?.
Use this string class extension
extension String {
func date(format: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.timeZone =TimeZone.current
let date = dateFormatter.date(from: self)
return date
}
}
use above function like this
let date = "07/06/2017 11:23 AM".date(format:"MM/dd/yyyy HH:mm a")
You can use this:
let df = DateFormatter()
df.dateFormat = "MM/dd/yyyy HH:mm a"
let date = df.string(from: dateString)
For more formats: http://nsdateformatter.com/.
I have this class with some optional properties:
class Address {
var Id: Int64
var AddressType: Int64
var AddressStatus: Int64
var Address1: String?
var Address2: String?
var City: String?
var State: String?
var Zip: String?
var Country: String?
var Latitude: Double?
var Longitude: Double?
}
I am trying to insert into a Sqlite database, like this:
let insert = table.insert(or: .replace, Id <- item.Id, AddressType <- item.AddressType, AddressStatus <- item.AddressStatus, Address1 <- item.Address1?, Address2 <- item.Address2?, City <- item.City?, State <- item.State?, Zip <- item.Zip?, Country <- item.Country?, Latitude <- item.Latitude?, Longitude <- item.Longitude?)
But I get this build error:
Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?
If I use '!' it will build, but I get this error when I run:
unexpectedly found nil while unwrapping an Optional value
I am still new to Swift, but from what I know, I don't want to use '!' when the value can be nil, correct?
I'm not sure what I'm doing wrong here.
Make all your class properties constants (declare with let) and make them non optional adding a required init() with all your Address properties parameters. BTW it is Swift convention to start your vars naming with a lowercase letter. Note: You should use Int instead of Int64 unless it is a requirement. Regarding the optionality of your properties you can just assign a default value for them at initialization time. Btw It is better to use a struct unless you need to make your object persist (NSCoding compliant):
struct Address {
let id: Int
let addressType: Int
let addressStatus: Int
let address1: String
let address2: String
let city: String
let state: String
let zip: String
let country: String
let latitude: Double?
let longitude: Double?
init(id: Int, addressType: Int, addressStatus: Int, address1: String = "", address2: String = "", city: String = "", state: String = "", zip: String = "", country: String = "", latitude: Double = nil, longitude: Double = nil) {
self.id = id
self.addressType = addressStatus
self.addressStatus = addressStatus
self.address1 = address1
self.address2 = address2
self.city = city
self.state = state
self.zip = zip
self.country = country
self.latitude = latitude
self.longitude = longitude
}
}
So you can create your new object Address as follow:
let address1 = Address(id: 1, addressType: 2, addressStatus: 3)
let address2 = Address(id: 2, addressType: 3, addressStatus: 4, address1: "Any Address", latitude: 22.0, longitude: 43.0) // You don't need to add all parameters as long as you keep them in the same order as your initializer
address2.latitude // 22.0