How to convert date string into date in swift 3 - swift3

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/.

Related

Log date on cell text change in Google Sheets

I'm trying to log the date in a cell when a user tries to enter a text in another cell. To give you a clearer picture, I would like today's date to be logged in cell B1 when a user writes something in A1. I used this formula in B1:
=IF(A1="","",B1=TODAY())
but it doesn't work! Any idea how I can do this?
paste this in B1 cell:
=IF(A1=""; ; TODAY())
note: the date will change daily
_______________________________________________________
otherwise, it would be:
function onEdit(e) {
var s = SpreadsheetApp.getActiveSheet();
if( s.getName() == "Sheet1" ) { // SHEET NAME
var r = s.getActiveCell();
if( r.getColumn() == 1 ) { // COLUMN OF ENTRY
var nextCell = r.offset(0, 1); // OFFSET +1 COLUMN
var newDate = Utilities.formatDate(new Date(),
"GMT+8", "MM/dd/yyyy"); // TIMEZONE + DATE FORMAT
nextCell.setValue(newDate);
}}}

how to convert array string to date swift 3

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]

How to format a date like "5 min", "1 hour,", "Yesterday", "1 Week ago"?

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?

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)

How to insert into Sqlite with optional parameters using Swift 3

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