I have created an IBOutlet to a date picker.
#IBOutlet weak var logDate: UIDatePicker!
I have also set the mode of this date picker to date.
Is there a way for me to extract the date that the user would input into the date picker?
I tried using print(logdate), however it also gives me the date along with the time. Like this 2015-10-30 07:10:03 +0000
Perhaps you want this:
let components = logDate.calendar.components([.Era, .Year, .Month, .Day],
fromDate: logDate.date)
print("\(components.era) \(components.year) \(components.month) \(components.day)")
// Output: 1 2015 10 31
Or perhaps you want this:
let formatter = NSDateFormatter()
formatter.calendar = logDate.calendar
formatter.dateStyle = .MediumStyle
formatter.timeStyle = .NoStyle
let dateString = formatter.stringFromDate(logDate.date)
print(dateString)
// Output: Oct 31, 2015
You can try another dateStyle setting, or be more explicit by setting the dateFormat property. The dateFormat syntax can get pretty hairy. Remember to use yyyy, not YYYY, for the year part of your format. But it's MM, not mm for the month part. Example:
formatter.dateFormat = "yyyy-MM-dd"
print(formatter.stringFromDate(logDate.date))
// Output: 2015-10-31
You can extract the date inputted by the user in a date field using this code.
Note: This solution extracts the input as a string
var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle // You can also use Long, Medium and No style.
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
var inputDate = dateFormatter.stringFromDate(*datepicker outlet name*.date)
print(inputDate)
Used a section of code from: http://www.ioscreator.com/tutorials/display-date-date-picker-ios8-swift
Swift 5
It's more simple than it appears. Just create a var of type Date and set its value from the datePicker outlet like this.
#IBOutlet weak var yourDatePicker: NSDatePicker!
var date = Date()
#IBAction func datePickerChanged(_ sender: Any) {
date = yourDatePicker.dateValue
}
Now you can use that variable to insert date values on Core Data's attributes of type Date or something like that.
Get hour and minute in swift 5
let comp = datePickerOutlet.calendar.dateComponents([.hour, .minute], from: datePickerOutlet.date)
print(comp.hour!)
print(comp.minute!)
Related
I am using date picker and selected datePicker mode as time. When I am loading the date picker it is showing current time.But I want to set default time always 5:00 PM.
I have tried the below way but it didn’t work for me.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
dateFormatter.timeZone = .current
if let date = dateFormatter.date(from: "17:00") {
datePicker.date = date
}
Please help me to default to time 5:00PM always. Thank you.
A possible solution is to get the current date and set hour, minute and second accordingly
let fivePM = Calendar.current.date(bySettingHour: 17, minute: 0, second: 0, of: Date())!
datePicker.date = fivePM
Another way is to set the countDownDuration property
datePicker.countDownDuration = 61200 // 17 * 3600
Another possible answer would be:
let cal = Calendar.current
let timeZone: TimeZone = .current
var dateComp = cal.dateComponents(in: timeZone, from: Date())
(dateComp.hour, dateComp.minute, dateComp.second, dateComp.nanosecond) = (17, 0, 0, 0)
let fivePM = cal.date(from: dateComp)
datePicker.date = fivePM
Using this technique you can also get 5pm of the time of another timezone.
Notice that when debugging in Xcode, Xcode will show all dates in the console in the GMT timezone.
I'm trying to format date in date picker. I can't seem to find the format to display date in 09-Nov-2014 format. It always displays in Nov 09, 2014 format. I did a lot of search but can't figure out which one is the correct format to input. Can anyone help me out? Tx in advance.
#objc func datePickerValueChanged(sender:UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.dateStyle = DateFormatter.Style.medium
dateFormatter.timeStyle = DateFormatter.Style.none
dateOfBirthTextField.text = dateFormatter.string(from: sender.date)
}
Don't set the styles. Just set the format.
You use either dateFormat or you use dateStyle and timeStyle.
Please note it's best to avoid using dateFormat for dates you wish to show to the user since your hardcoded format won't be standard for most users.
Also be aware that MM show the month number. If you want the abbreviated month name, use MMM.
You should not use dateStyle & timeStyle here you need a specific date format, your code should look like,
#objc func datePickerValueChanged(sender:UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateOfBirthTextField.text = dateFormatter.string(from: sender.date)
}
Hope it helps.
I am trying to use the UILabel and DateFormatter to display the time (date, min, sec) whenever a user launches the APP.
I currently found this from stackoverflow
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
but it seems that I have to pass in a time into the formatter. How do I just get the UILabel to display the current time instead of a fixed time?
If you want to show the current time without passing any variables, You do so by:
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let exactlyCurrentTime: Date = Date()
print(dateFormatterPrint.stringFromDate(exactlyCurrentTime))
// e.g Set your label text:
myLabel.text = "Current Time: \(dateFormatterPrint.stringFromDate(exactlyCurrentTime))"
For example, If we want: Friday, Nov 16, 2018 | We set: EEEE, MMM d, yyyy
I do also recommend a visit of NSDateFormatter.com to understand how dateFormat works.
Best of luck
label.text = dateFormatter.string(from: Date())
I generate a NSDate object from string.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
let stringToDate = dateFormatter.dateFromString(dateFromService) // 2015-07-20 12:00:43 +0000
I get this string value from webserver. I need to modify for personal device timezone. Want to add hours this stringToDate object but not work
var addHours : Int = 2 // 2 hours will be added
var newDate = stringToDate.dateByAddingTimeInterval(addHours)
Use NSCalendarComponents:
let calendar = NSCalendar.currentCalendar()
let newDate = calendar.dateByAddingUnit(
.CalendarUnitHour, // adding hours
value: 2, // adding two hours
toDate: oldDate,
options: .allZeros
)
Using NSCalendar will account for things like leap seconds, leap hours, etc.
But as Duncan C's answer points out, simply adding hours is definitely the wrong approach. Two time zones won't always be separated by the same amount of time. Again, this is something especially true when we take daylight savings into account. (For example, the United States doesn't start/end daylight savings on the same days as Europe, and Arizona doesn't even do daylight savings).
You're asking the wrong question. This is what's known as an "XY Problem".
You should be asking "How do I display a date string I get from a web server in the user's local time zone."
NSDate represents a date/time in an abstract form that does not contain a time zone. You convert it to a specific time zone for display. Do not try to add/subtract hours to an NSDate to offset for time zones. That is the wrong approach.
The correct answer is simple. Create a second date formatter and don't set it's timezone to GMT. It defaults to the user's local time zone.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
let date = dateFormatter.dateFromString(dateFromService)
let outputDatedateFormatter = NSDateFormatter()
outputDatedateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
//leave the time zone at the default (user's time zone)
let displayString = outputDateFormatter.stringFromDate(date)
println("Date in local time zone = \(displayString)")
For Swift 3 you can use this function:
//get next date by adding hours func
getNewDateAfterAddingHours(hoursToAdd:NSInteger, oldDate:Date) -> Int64 {
let calendar = Calendar.current
let newDate = calendar.date(byAdding: .hour, value: hoursToAdd, to: oldDate)
return Int64((newDate?.timeIntervalSince1970)!)
}
If you are doing it more often, check out library called SwiftMoment (inspired by the same .js library), which allows you to do following (and much more!):
// Create date using moment library
let myDate = moment(myString)
// Add one hour
let dateWithAddedHour = myDate + 1.hours
Moment is a wrapper around NSDate instance, while Duration (which is what you get from Int.hours, Int.minutes etc.) wraps an NSTimeInterval value.
Implementing this should take you just a moment! (Pun intended).
I think the question is pretty straightforward. I need only the date to appear, and not the time. Couldn't find anything for Swift, so my code is here:
cell.date.text = NSDateFormatter.localizedStringFromDate(dates[indexPath.row],
dateStyle: .ShortStyle,
timeStyle: .ShortStyle)
Read the documentation of the method you are calling. There are four or five different possible values that you can pass for the formatting style of the date and the time. You picked a formatting style that outputs a short format. Pick instead the formatting style that does what you want. I'll give you a hint: There is one style with a "No" in the name.
Seriously, right click on "ShortStyle", and pick "Jump to Definition" from the popup menu.
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.locale = NSLocale(localeIdentifier: #"en_US")
let d = NSDate()
let s = dateFormatter.stringFromDate(d)
Use this
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let d = NSDate()
cell.date.text = dateFormatter.stringFromDate(d)