I have variable with data type Date, where I have stored date in this format
2018-12-24 18:00:00 UTC
How can I get from this day or month?
var lastMonthDate = Calendar. current. date(byAdding: . month, value: -1, to: date) calendar.
Same strategy as @MartinR answer, as short as possible: let cal = NSCalendar. currentCalendar() let date = NSDate() var result = map(-6... 0) { delta -> Int in cal.
I created a method that is supposed to take in a string in "YYYY-MM-DD" form and spit out an int that represents the dates position in relation to the week it is in (regardless if it overlaps between months). So e.g sunday=1 monday=2 and so on.
The great thing about working with dates and times in Swift 5 is that the Calendar class is that it does its best to work with the DateComponents that you give it, and DateComponents gives you all sorts of ways to specify a date.
The Date struct, which stores date and times in Swift 5. The Calendar struct, which represents one of 16 different calendar systems, and provides a meaningful context for Date s. The DateComponents struct, which a collection of date and time components, such as years, months, days, hours, minutes, and so on.
timeIntervalSinceReferenceDate: The number of seconds before or after the Swift reference date, expressed as a TimeInterval (which is just a typealias for Double ). Positive values denote seconds after the reference date, negative values denote seconds before the reference date.
One of the more common tasks when working with dates is to extract the different parts of the date. For example, sometimes we only want the year, or the month. Other times we might want the day of the week.
How to convert string to Date
extension Date { func get(_ components: Calendar.Component..., calendar: Calendar = Calendar.current) -> DateComponents { return calendar.dateComponents(Set(components), from: self) } func get(_ component: Calendar.Component, calendar: Calendar = Calendar.current) -> Int { return calendar.component(component, from: self) } }
let date = Date() // MARK: Way 1 let components = date.get(.day, .month, .year) if let day = components.day, let month = components.month, let year = components.year { print("day: \(day), month: \(month), year: \(year)") } // MARK: Way 2 print("day: \(date.get(.day)), month: \(date.get(.month)), year: \(date.get(.year))")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With