By default, the date picker shows 1 - January - 2014.
Can user pick as
1 - 1 - 2014 ?
How? Thanks!
You can't change the date picker to that format. Apple provides you the following datepicker modes, each of them has its own format:
UIDatePickerModeTime
The date picker displays hours, minutes, and (optionally) an AM/PM designation. The exact items shown and their order depend upon the locale set. An example of this mode is [ 6 | 53 | PM ].
UIDatePickerModeDate
The date picker displays months, days of the month, and years. The exact order of
these items depends on the locale setting. An example of this mode is
[ November | 15 | 2007 ].
UIDatePickerModeDateAndTime
The date picker displays dates (as unified day of the week, month, and day of
the month values) plus hours, minutes, and (optionally) an AM/PM
designation. The exact order and format of these items depends on the
locale set. An example of this mode is [ Wed Nov 15 | 6 | 53 | PM ].
UIDatePickerModeCountDownTimer
The date picker displays hour and minute values, for example [ 1 | 53 ].
The application must set a timer to fire at the proper interval and
set the date picker as the seconds tick down.
If you want any other format, you must implement your own datePicker.
#Luis is right, if you want the month in numbers you can get. below code will not change how UIDatePicker shows month. but will change your selected month in number. and you can pick as 1 - 1 - 2014.
NSDateFormatter *date = [[NSDateFormatter alloc]init];
[date setDateFormat:#"dd-M-YYYY"];
YourDatepicker.datePickerMode = UIDatePickerModeDate;
NSString *date1 = [date stringFromDate:YourDatepicker.date];
date1 will give you the 1 - 1 - 2014.
func datePickerValueChanged(sender:UIDatePicker) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MMM-yyyy"
let dateString = dateFormatter.stringFromDate(sender.date)
departureDateTextField.text = dateString
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am trying to add a month to an NSDate. However, I discovered that the following code only works when the month number is between 1 and 11. When you add 1 to 12, it does not automatically roll as a modulus to make 13->1 nor does it increment the year.
newStartDate = [cal dateByAddingUnit:NSCalendarUnitMonth value:1 toDate:startDate options:0];
On the other hand, if you add seconds which does seem to work as modulus math, the seconds in a month vary by month and I would hate to have to code all those possibilities by hand.
//following requires an input for days in month which can be
28,29,30 or 31 depending on month and leap year status not to mention DST issues
newStartDate = [newStartDate dateByAddingTimeInterval:30 * 24 * 60 * 60];
Can any one recommend a simple way to increment a date by one month?
Thanks in advance for any suggestions.
Edit.
It turns out this behavior of the month incrementing up to 12 and then stopping in my project seems to be due to a loop in which it is embedded. So the method with options:0 by itself does increment higher units as expected. Other options behave differently.
When you add 1 to 12, it does not automatically roll as a modulus to make 13->1 nor does it increment the year.
You're calling the wrong method. Call this method instead:
let cal = Calendar(identifier: .gregorian)
let d = cal.date(from: DateComponents(
year: 2018, month: 12, day: 26, hour: 11, minute: 0, second: 0))!
let d2 = cal.date(byAdding: DateComponents(month:1), to: d)
d2 // Jan 26, 2019 at 11:00 AM
NSDate *actualDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComp = [NSDateComponents new];
[dateComp setMonth:1];
NSDate *dateAfterOneMonth = [calendar dateByAddingComponents:dateComp toDate:actualDate options:0];
NSLog(#"Date after One Month: %#", dateAfterOneMonth);
I now that there is a thread that discussing about minimum and maximum date time in here Minimum and maximum date in UIDatePicker
but I am a beginner now in programming, and I have little bit confused with date and time object. I have tried but I can't set up my date time picker properly. So I want to set my date time picker to have minimum and maximum limited time.
the minimum is Now, and the maximum is 1 month from now. what code do I have to use? Thanks in advance
https://i.stack.imgur.com/RxXUX.png
You can try
self.datePicker.minimumDate = Date()
self.datePicker.maximumDate = Calendar.current.date(byAdding: .day, value: 30 , to:Date())!
or
self.datePicker.maximumDate = Calendar.current.date(byAdding: .month, value: 1 , to:Date())!
I recommend to use the date math skills of Calendar. It calculates the same day in the next month. If the day does not exist (for example Feb 30) it returns the next closest available date.
let now = Date()
let calendar = Calendar.current
let dayComponents = calendar.dateComponents([.day], from: now)
let maximumDate = calendar.nextDate(after: now, matching: dayComponents, matchingPolicy: .nextTime)
To get a Date exactly one month in the future from now (taking into account different month lengths), you can use Date.date(byAdding:value:to:), e.g. as in this answer. You'd take the result and set it as maximumDate of your picker.
Hello I am getting the starting day number of the week in this way
NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
[formatter setDateFormat:#"c"];
NSString *dayofweek=[formatter stringFromDate:startdate];
This strdate is a like 11/01/2016.
Then I convert it into a intand my button width is 41 so I take the X position where should I place this starting date button in this way.
int wday=[dayofweek intValue];
posx=41*wday;
My days name arranged like this.
S M T W TH F S
My problem is when I change my phone region to Austrailia it takes this wday as 3. But If I changed the region to an Asian country wday takes as 2.
How can I solve this issue?
Please help me.
Thanks
To get a locale-independent weekday use:
NSInteger weekday = [[NSCalendar autoupdatingCurrentCalendar]
components:NSCalendarUnitWeekday
fromDate:startDate].weekday;
How can I get the exact difference (in decimal) between 2 values of NSDate.
Eg. Jan 15 2016 to Jul 15 2017 = 1.5 Years.
I can use something like:
NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitYear, fromDate: date1, toDate: date1, options: nil).year
but this gives me absolute values. i.e. for above example it would give me 1 Year. Is it possible to get exact values correct to at least a few decimal places?
The terms you've used here are misleading. When you say "absolute" you mean "integral." And when you say "exact" you mean "within some desired precision."
Let's say the precision you wanted was 2 decimal places, so we'd need to measure a year to 1%. That's larger than a day, so tracking days is sufficient. If you needed more precision, then you could expand this technique, but if you push it too far, "year" gets more tricky, and you have to start asking what you mean by "a year."
Avoid asking this question when you can. Many answers here say things like "there are 365.25 days in a year." But try adding "365.25 * 24 hours" to "right now" and see if you get "the same date and time next year." While it may seem correct "on average," it is actually wrong 100% of the time for calendar dates. (It works out here because it's within 1%, but so would 365, 366, or even 363.)
We avoid this madness by saying "1% is close enough for this problem."
// What calendar do you *really* mean here? The user's current calendar,
// or the Gregorian calendar? The below code should work for any calendar,
// because every calendar's year is made up of some number of days, but it's
// worth considering if you really mean (and are testing) arbitrary calendars.
// If you mean "Gregorian," then use NSCalendar(identifier: NSCalendarIdentifierGregorian)!
let calendar = NSCalendar.currentCalendar()
// Determine how many integral days are between the dates
let diff = calendar.components(.Day, fromDate: date1, toDate: date2, options: [])
// Determine how many days are in a year. If you really meant "Gregorian" above, and
// so used calendarWithIdentifer rather than currentCalendar, you can estimate 365 here.
// Being within one day is inside the noise floor of 1%.
// Yes, this is harder than you'd think. This is based on MartinR's code: http://stackoverflow.com/a/16812482/97337
var startOfYear: NSDate? = nil
var lengthOfYear = NSTimeInterval(0)
calendar.rangeOfUnit(.Year, startDate: &startOfYear, interval: &lengthOfYear, forDate: date1)
let endOfYear = startOfYear!.dateByAddingTimeInterval(lengthOfYear)
let daysInYear = calendar.components(.Day, fromDate: startOfYear!, toDate: endOfYear, options: []).day
// Divide
let fracDiff = Double(diff.day) / Double(daysInYear)
That said, in most cases you shouldn't be doing this. Since iOS 8, the preferred tool is NSDateComponentsFormatter. You won't get this precise format (i.e. fractional years), but you'll get a nicely localized result that takes most issues into account across different cultures.
let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = .Full
formatter.includesApproximationPhrase = true
formatter.allowedUnits = [.Year, .Month]
formatter.allowsFractionalUnits = true
formatter.stringFromDate(date1, toDate: date2)
// About 1 year, 6 months
Since you mentioned that your goal is something you can display to users as a meaningful indication of the time between two dates, you might find it easier to use NSDateComponentsFormatter. For example:
let dateStr1 = "Jan 15 2016"
let dateStr2 = "Jul 15 2017"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM dd yyyy"
if let date1 = dateFormatter.dateFromString(dateStr1),
let date2 = dateFormatter.dateFromString(dateStr2) {
let dateComponentsFormatter = NSDateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.Year, .Month]
dateComponentsFormatter.unitsStyle = .Full
let difference = dateComponentsFormatter.stringFromDate(date1, toDate: date2)
}
This gives you a string that reads "1 year, 6 months". It's not exactly what you specified as your goal, but it's a clear indication for users and avoids a lot of complexity. There's a property on NSDateComponentsFormatter called allowsFractionalUnits that's supposed to lead to results like "1.5 years", but it doesn't seem to work right now. (Even if you limit the allowedUnits to only .Year, you still don't get a fractional year. I'm off to file a bug with Apple...). You can tweak allowedUnits to get whatever granularity you like, and use includesApproximationPhrase to have the class add a localized version of "About..." to the resulting string if it's not precise. If you have some flexibility in your final format, this would be a really good solution.
There isn't a perfect answer to this question. Different years are slightly different lengths. You have to make some assumptions.
If you assume 365.2425 days per year, with each day having 24 hours, then the calculation is trivial:
let secondsPerYear: NSTimeInterval = NSTimeInterval(365.2425 * 24 * 60 * 60)
let secondsBetweenDates =
date2.timeIntervalSinceReferenceDate - date1.timeIntervalSinceReferenceDate;
let yearsBetweenDates = secondsBetweenDates / secondPerYear
But there are lots of edge cases and weirdness to deal with. Because of leap years, some years have 365 days, and some have 366. Then there's leap seconds.
If you get rid of months in #CodeDifferent's answer then you'll get an answer that allows for leap days between the dates.
But, as Code Different pointed out, his answer as written actually gives answers that seem more accurate, even though they are not. (A difference of 3 months will always yield .25 years, and will ignore longer/shorter months. Is that the right thing to do? Depends on your goal and your assumptions.)
According to NASA, there are 365.2422 days per year on average. Here, I round that up to 365.25 days per year:
let components = NSCalendar.currentCalendar().components([.Year, .Month, .Day], fromDate: fromDate, toDate: toDate, options: [])
var totalYears = Double(components.year)
totalYears += Double(components.month) / 12.0
totalYears += Double(components.day) / 365.25
Obviously, this depends on your assumptions. If you want to count of leap days between fromDate and toDate, it will be more complicated.
Some sample outputs:
From date To date Total Years
------------ ------------ ------------
Jan 15, 2016 Jul 15, 2017 1.5
Jan 15, 2016 Apr 14, 2016 0.25
Jan 15, 2016 Aug 15, 2017 1.5833
Jan 15, 2016 Jan 14, 2018 1.9988
This is an issue that I have been having for quite some time, and I cannot for the life of me get it fixed properly. Using the RSS Feed http://www.localendar.com/public/RogerJohnson?style=M3,
I have my app set up to parse the XML and list each calendar entry into the row of a TableView. The issue pops up when DST begins. Localendar doesn't have a feature for checking if an event occurs in DST, so in the RSS feed the pubDate always shows as:
Fri, 02 May 2014 19:00:00 EST
The event for that day actually begins at 7:00 PM EDT. So, when the app converts everything around, it takes the EST to heart, and knowing it is currently in DST, displays the time as 20:00:00 EDT. How can I properly set this NSDate so that no matter if it is DST or not, it will show 7:00 instead of adjusting by an hour?
Here is how I am parsing the RSS:
NSString *articleDateString = [item valueForChild:#"pubDate"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC822];
NSLog(#"%#", articleDate);
RSSEntryCalendar *entry = [[[RSSEntryCalendar alloc] initWithBlogTitle:blogTitle articleTitle:articleTitle articleUrl:articleUrl articleDate:articleDate articleImage:bodyoftext] autorelease];
Then, displaying in table view I have for cellForRowAtIndexPath:
RSSEntryCalendar *entry = [_allEntries objectAtIndex:indexPath.row];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"America/New_York"]];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
cell.detailTextLabel.text = articleDateString;
As mentioned before, pubDate always shows EST, regardless of DST being in effect or not. If it shows 19:00:00 it should be 7, regardless of time of year, but is constantly changing during DST.
I put in a NSLog for the NSDate where I parse it, and here is what I get for one entry:
2014-05-03 00:00:00 +0000
The time that shows up in the table view is May 2nd, 2014 8:00PM, while the actual event occurs at May 2nd, 2014 7:00PM. Hopefully this helps to demonstrate issue.
Per the RSS 2.0 Specification:
All date-times in RSS conform to the Date and Time Specification of RFC 822, with the exception that the year may be expressed with two characters or four characters (four preferred).
Per RFC 822:
zone = "UT" / "GMT" ; Universal Time
; North American : UT
/ "EST" / "EDT" ; Eastern: - 5/ - 4
/ "CST" / "CDT" ; Central: - 6/ - 5
/ "MST" / "MDT" ; Mountain: - 7/ - 6
/ "PST" / "PDT" ; Pacific: - 8/ - 7
/ 1ALPHA ; Military: Z = UT;
; A:-1; (J not used)
; M:-12; N:+1; Y:+12
/ ( ("+" / "-") 4DIGIT ) ; Local differential
; hours+min. (HHMM)
As you can see RFC 822 dates have a very limited set of time zone abbreviations - but they are in the spec and they have very specific meaning. "EST" = UTC-5.
If the service you're using (Localendar) is erroneously sending back EST when they mean EDT - that's a bug you should take up with them. They are not properly adhering to the RSS spec.
Working around the bug in your own code is possible - but it's not the best idea:
One day they might fix it, and then your code could be broken.
Local times can be ambiguous during the fall-back daylight saving time transition. A value like "Sun, 2 Nov 2014 01:30:00 EST" should have a singular meaning, separate from "Sun, 2 Nov 2014 01:30:00 EDT". By assuming EST=ET, then you have no way to tell these two points apart.