Get just the date (no time) from UIDatePicker - swift

I am trying to get just the date from UIDatePicker:
myDatePicker.datePickerMode = UIDatePicker.Mode.date
var selectedDate=myDatePicker.date
println(selectedDate)
However, this prints more than the date (it prints 2015-04-09 21:45:13 +0000). How do I get just the date part (without the time)? I also set the date picker Mode property to Date.

According to the Apple's documentation datePicker.mode should be date so you can use DateFormatter like so
Swift 4
datePicker.datePickerMode = UIDatePicker.Mode.date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMMM yyyy"
let selectedDate = dateFormatter.string(from: datePicker.date)
print(selectedDate)

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yy"
let dateString = dateFormatter.stringFromDate(myDatePicker.date)
You can print dateString, assign it to a label, whatever. The format will be
04/09/15

Swift 3/4, this will print a string of type Mar 08, 2017
datePicker.datePickerMode = .date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"
let selectedDate = dateFormatter.string(from: datePicker.date)
print(selectedDate)

I just want to add my bit in on here after coming across a similar problem. I would follow shades answer for String display of date. Not the from XCode 7 and swift 2 onwards when you use a UIDatePicker set the following to only view dates in the Picker:
#IBOutlet weak var datePicker: UIDatePicker!
datePicker.datePickerMode = .Date

Swift 4.0 version code is here
#IBAction func saveDateAction(_ sender: Any) {
myDatePicker.datePickerMode = UIDatePicker.Mode.date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
let selectedDate = dateFormatter.string(from: myDatePicker.date)
print("selectedDate",selectedDate)
}

Date picker date :
let date = datePicker.date
let dateConverted = Date.init(year: date.GetYear(), month: date.GetMonth(), day: date.GetDay())
//dateConverted result = 2019-02-27 00:00:00 +0000
let predicate = NSPredicate(format: "booking_date == %#", dateConverted as CVarArg)
Use this extensions:
extension Date {
init(year: Int, month: Int, day: Int) {
var dc = DateComponents()
dc.year = year
dc.month = month
dc.day = day
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
if let date = calendar.date(from: dc) {
self.init(timeInterval: 0, since: date)
} else {
fatalError("Date component values were invalid.")
}
}
func GetYear() -> Int {
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
let components = calendar.components([.day , .month , .year], from: self)
return components.year!
}
func GetMonth() -> Int {
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
let components = calendar.components([.day , .month , .year], from: self)
return components.month!
}
func GetDay() -> Int {
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
let components = calendar.components([.day , .month , .year], from: self)
return components.day!
}
}

Related

SwiftUI string to formatted date (ISO)

can you please help me with that topic?
from the API i get the following date as a string: 2021-05-21T14:35:15.647+02:00
How can i convert this to a date object, so that i can format it?
I tried it in different ways as subscribed here in stackoverflow or in other tutorials, like this:
let date = "2021-05-21T14:35:15.647+02:00"
func formatStringDate(date: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let newDate = dateFormatter.date(from: date)
dateFormatter.setLocalizedDateFormatFromTemplate("MMMM d, yyyy")
return dateFormatter.string(from: newDate!)
}
var newDate = formatStringDate(date: date)
print(newDate)
or
let timestampString = "2018-12-09T11:08:48-05:00"
if let date = isoDateFormatter.date(from: timestampString) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM, dd, yyyy h:mm a"
let dateFormattedString = dateFormatter.string(from: date)
print(dateFormattedString) // December, 09, 2018 11:08 AM
} else {
print("not a valid date")
}
But it´s not working.
Thanks for your help
Thanks for your help, i got the following snippet to work:
let dateString = "2021-05-21T14:35:15.647+02:00"
let inputFormatter = ISO8601DateFormatter()
inputFormatter.formatOptions = [
.withFractionalSeconds,
.withFullDate
]
let date = inputFormatter.date(from: dateString)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.YYYY"
print(dateFormatter.string(from: date!))
Thanks

swift 4 Date from from ISO string to custom format?

I have ISO date from API I want to convert it to another custom date format, I've checked some threads here it's look like I have to use the extension on Date class, unfortunately, all my attempts failed.
this example for date i have :
2014-10-22T00:00:00+00:00
I want to convert it to July 2014
can I use normal Date class to do it?
and below what I am trying to do
let formatter = ISO8601DateFormatter()
let date = formatter.date(from: "2016-08-26T12:39:00Z")
let string = formatter.string(from: Date())
Try it:
let formatter = ISO8601DateFormatter()
if let date = formatter.date(from: "2014-10-22T00:00:00+00:00") {
let string = date.stringDate
print(string) // October 2014
}
extension Date {
var stringDate: String {
let formatter = DateFormatter()
formatter.dateFormat = "MMMM yyyy"
return formatter.string(from: self)
}
}
my Date load from SQL Server and format like this "2018-01-17T03:08:28.158769" the code below is work for me perfectly
let isoDate = "2018-01-17T03:08:28.158769"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
let date = dateFormatter.date(from:isoDate!)!
dateFormatter.dateFormat = "d.MMMM.YYYY"
let displayDate = dateFormatter.string(from: date)
displayDateInLabel.text = displayDate
result
17.January.2018
You can get Month and Year like this
override func viewDidLoad() {
super.viewDidLoad()
print(getFormattedDate(date: Date()))
}
func getFormattedDate(date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM YYYY"
let strMonth = dateFormatter.string(from: date)
return strMonth
}

How to calculate age with days/month/year using date picker? [duplicate]

I am trying calculate the age from birthdayDate in Swift with this function:
var calendar : NSCalendar = NSCalendar.currentCalendar()
var dateComponentNow : NSDateComponents = calendar.components(
NSCalendarUnit.CalendarUnitYear,
fromDate: birthday,
toDate: age,
options: 0)
But I get an error Extra argument toDate in call
In objective c this was the code, but I don't know why get this error:
NSDate* birthday = ...;
NSDate* now = [NSDate date];
NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
components:NSYearCalendarUnit
fromDate:birthday
toDate:now
options:0];
NSInteger age = [ageComponents year];
Is there correct form better than this?
You get an error message because 0 is not a valid value for NSCalendarOptions.
For "no options", use NSCalendarOptions(0) or simply nil:
let ageComponents = calendar.components(.CalendarUnitYear,
fromDate: birthday,
toDate: now,
options: nil)
let age = ageComponents.year
(Specifying nil is possible because NSCalendarOptions conforms to the RawOptionSetType protocol which in turn inherits
from NilLiteralConvertible.)
Update for Swift 2:
let ageComponents = calendar.components(.Year,
fromDate: birthday,
toDate: now,
options: [])
Update for Swift 3:
Assuming that the Swift 3 types Date and Calendar are used:
let now = Date()
let birthday: Date = ...
let calendar = Calendar.current
let ageComponents = calendar.dateComponents([.year], from: birthday, to: now)
let age = ageComponents.year!
I create this method its very easy just put the birthday date in the method and this will return the Age as a Int
Swift 3
func calcAge(birthday: String) -> Int {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
let birthdayDate = dateFormater.date(from: birthday)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
let now = Date()
let calcAge = calendar.components(.year, from: birthdayDate!, to: now, options: [])
let age = calcAge.year
return age!
}
Swift 2
func calcAge(birthday: String) -> Int{
let dateFormater = NSDateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
let birthdayDate = dateFormater.dateFromString(birthday)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let now: NSDate! = NSDate()
let calcAge = calendar.components(.Year, fromDate: birthdayDate!, toDate: now, options: [])
let age = calcAge.year
return age
}
Usage
print(calcAge("06/29/1988"))
For swift 4 works fine
func getAgeFromDOF(date: String) -> (Int,Int,Int) {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "YYYY-MM-dd"
let dateOfBirth = dateFormater.date(from: date)
let calender = Calendar.current
let dateComponent = calender.dateComponents([.year, .month, .day], from:
dateOfBirth!, to: Date())
return (dateComponent.year!, dateComponent.month!, dateComponent.day!)
}
let age = getAgeFromDOF(date: "2000-12-01")
print("\(age.0) Year, \(age.1) Month, \(age.2) Day")
This works for Swift 3
let myDOB = Calendar.current.date(from: DateComponents(year: 1994, month: 9, day: 10))!
let myAge = Calendar.current.dateComponents([.month], from: myDOB, to: Date()).month!
let years = myAge / 12
let months = myAge % 12
print("Age : \(years).\(months)")
This is working in swift 3 for me..
let now = NSDate()
let calendar : NSCalendar = NSCalendar.current as NSCalendar
let ageComponents = calendar.components(.year, from: datePickerView.date, to: now as Date, options: [])
let age = ageComponents.year!
ageCalculated.text = String(age)
Thanks to #Martin R
//Create string extension to make more easy
extension String {
func getDate(format: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter.date(from: self) ?? Date()
}
}
Get today's date and your birthday date
let today = Date()
let birthDate = "1990-01-01".getDate(format: "yyyy-MM-dd")
Create an instance of the user's current calendar
let calendar = Calendar.current
Use calendar to get difference between two dates
let components = calendar.dateComponents([.year, .month, .day], from: birthDate, to: today)
let ageYears = components.year //get how many years old
let ageMonths = components.month //extra months
let ageDays = components.day // extra days
This is the best way on swift 5
lazy var dateFormatter : DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
let birthday = dateFormatter.date(from: "1980-04-25")
let timeInterval = birthday?.timeIntervalSinceNow
let age = abs(Int(timeInterval! / 31556926.0))

NSDateFormatter subtracting a day when removing time

I am trying to remove time from date using NSDateFormatter. This is the code:
func dateWithOutTime( datDate: NSDate?) -> NSDate {
let formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let stringDate: String = formatter.stringFromDate(datDate!)
let dateFromString = formatter.dateFromString(stringDate)
return dateFromString!
}
If i send in ex 04-01-2016 12:00:00, the return is 03-01-2016 23:00:00
I have tried changing the dateFormat, but it still keeps to subtracting a day from the date... Why? Please Help :)
The easiest way is to use startOfDayForDate of NSCalendar
Swift 2:
func dateWithOutTime( datDate: NSDate) -> NSDate {
return NSCalendar.currentCalendar().startOfDayForDate(datDate)
}
Swift 3+:
func dateWithOutTime(datDate: Date) -> Date {
return Calendar.current.startOfDay(for: datDate)
}
or to adjust the time zone to UTC/GMT
Swift 2:
func dateWithOutTime( datDate: NSDate) -> NSDate {
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
calendar.timeZone = NSTimeZone(forSecondsFromGMT: 0)
return calendar.startOfDayForDate(datDate)
}
Swift 3+:
func dateWithOutTime(datDate: Date) -> Date {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
return calendar.startOfDay(for: datDate)
}
Two things:
(a) This can be done without using NSDateFormatter. (b) Calling print(aDate) will give you the UTC time, not in your local time. After losing too many brain cells trying to mentally convert back and forth, I decided to make an extension to NSDate to print it in my local timezone.
// NSDateFormatter is expensive to create. Create it once and reuse
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZZ"
extension NSDate {
// This will print the date in the local timezone
var localTime: String {
return dateFormatter.stringFromDate(self)
}
}
func dateWithOutTime(datDate: NSDate?) -> NSDate {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .Day], fromDate: datDate!)
return calendar.dateFromComponents(components)!
}
let datDate = NSCalendar.currentCalendar().dateWithEra(1, year: 2016, month: 1, day: 4, hour: 12, minute: 0, second: 0, nanosecond: 0)
let result = dateWithOutTime(datDate)
print(result.localTime)

Calculate age from birth date using NSDateComponents in Swift

I am trying calculate the age from birthdayDate in Swift with this function:
var calendar : NSCalendar = NSCalendar.currentCalendar()
var dateComponentNow : NSDateComponents = calendar.components(
NSCalendarUnit.CalendarUnitYear,
fromDate: birthday,
toDate: age,
options: 0)
But I get an error Extra argument toDate in call
In objective c this was the code, but I don't know why get this error:
NSDate* birthday = ...;
NSDate* now = [NSDate date];
NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
components:NSYearCalendarUnit
fromDate:birthday
toDate:now
options:0];
NSInteger age = [ageComponents year];
Is there correct form better than this?
You get an error message because 0 is not a valid value for NSCalendarOptions.
For "no options", use NSCalendarOptions(0) or simply nil:
let ageComponents = calendar.components(.CalendarUnitYear,
fromDate: birthday,
toDate: now,
options: nil)
let age = ageComponents.year
(Specifying nil is possible because NSCalendarOptions conforms to the RawOptionSetType protocol which in turn inherits
from NilLiteralConvertible.)
Update for Swift 2:
let ageComponents = calendar.components(.Year,
fromDate: birthday,
toDate: now,
options: [])
Update for Swift 3:
Assuming that the Swift 3 types Date and Calendar are used:
let now = Date()
let birthday: Date = ...
let calendar = Calendar.current
let ageComponents = calendar.dateComponents([.year], from: birthday, to: now)
let age = ageComponents.year!
I create this method its very easy just put the birthday date in the method and this will return the Age as a Int
Swift 3
func calcAge(birthday: String) -> Int {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
let birthdayDate = dateFormater.date(from: birthday)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
let now = Date()
let calcAge = calendar.components(.year, from: birthdayDate!, to: now, options: [])
let age = calcAge.year
return age!
}
Swift 2
func calcAge(birthday: String) -> Int{
let dateFormater = NSDateFormatter()
dateFormater.dateFormat = "MM/dd/yyyy"
let birthdayDate = dateFormater.dateFromString(birthday)
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let now: NSDate! = NSDate()
let calcAge = calendar.components(.Year, fromDate: birthdayDate!, toDate: now, options: [])
let age = calcAge.year
return age
}
Usage
print(calcAge("06/29/1988"))
For swift 4 works fine
func getAgeFromDOF(date: String) -> (Int,Int,Int) {
let dateFormater = DateFormatter()
dateFormater.dateFormat = "YYYY-MM-dd"
let dateOfBirth = dateFormater.date(from: date)
let calender = Calendar.current
let dateComponent = calender.dateComponents([.year, .month, .day], from:
dateOfBirth!, to: Date())
return (dateComponent.year!, dateComponent.month!, dateComponent.day!)
}
let age = getAgeFromDOF(date: "2000-12-01")
print("\(age.0) Year, \(age.1) Month, \(age.2) Day")
This works for Swift 3
let myDOB = Calendar.current.date(from: DateComponents(year: 1994, month: 9, day: 10))!
let myAge = Calendar.current.dateComponents([.month], from: myDOB, to: Date()).month!
let years = myAge / 12
let months = myAge % 12
print("Age : \(years).\(months)")
This is working in swift 3 for me..
let now = NSDate()
let calendar : NSCalendar = NSCalendar.current as NSCalendar
let ageComponents = calendar.components(.year, from: datePickerView.date, to: now as Date, options: [])
let age = ageComponents.year!
ageCalculated.text = String(age)
Thanks to #Martin R
//Create string extension to make more easy
extension String {
func getDate(format: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return dateFormatter.date(from: self) ?? Date()
}
}
Get today's date and your birthday date
let today = Date()
let birthDate = "1990-01-01".getDate(format: "yyyy-MM-dd")
Create an instance of the user's current calendar
let calendar = Calendar.current
Use calendar to get difference between two dates
let components = calendar.dateComponents([.year, .month, .day], from: birthDate, to: today)
let ageYears = components.year //get how many years old
let ageMonths = components.month //extra months
let ageDays = components.day // extra days
This is the best way on swift 5
lazy var dateFormatter : DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
let birthday = dateFormatter.date(from: "1980-04-25")
let timeInterval = birthday?.timeIntervalSinceNow
let age = abs(Int(timeInterval! / 31556926.0))