How to always get seconds value "00" for UIDatePicker's date?
Now I am getting value like this format 5:30:45, I need to get this format of time 5:30:00.
How to achieve this?
I used this code it is working fine.
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit ) fromDate:datePicker.date];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:datePicker.date];
[dateComponents setHour:[timeComponents hour]];
[dateComponents setMinute:[timeComponents minute]];
[dateComponents setSecond:0.0];
NSDate *newDate = [calendar dateFromComponents:dateComponents];
You don't have to juggle with the NSDateComponents or convert the date to a string and back. You just can tell the calendar to set the date to the beginning of the minute (hour/date/week/…)
NSDate *date = self.datePicker.date;
[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitMinute
startDate:&date
interval:NULL
forDate:date];
//date now is set to the beginning of the minute -> seconds == 00
NSDate *currentDate = [datePicker date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *Str_Seccond=[dateFormatter stringFromDate:currentDate];
In Str_Seccond string you can get the seconds in string format.
Swift 4 version :
let calendar = NSCalendar.current
let components = calendar.dateComponents([.year, .month, .day,
.hour, .minute],
from: yourDate)
let date = calendar.date(from: components)
NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
[dateformatter setDateFormat:#"ss"];
NSLog(#"%#",[dateformatter stringFromDate:[datePicker date]]);
In Swift:
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .Day, .Hour, .Minute], fromDate: datePicker.date)
let date = calendar.dateFromComponents(components)
Related
I know there's a few questions already on this but I keep running into the same error regardless of what I do to my code. I am working in the simulator, I have location set to my long/lat. When I try to convert the current date to zero hours, minutes, seconds I always get this result:
2015-07-10 08:53:19.868 xxxxxxxxxxxxxxxxx[2184:7462272] Today at start of day:2015-07-10 04:00:00 +0000
Here's my code:
NSDate* today = [[NSDate alloc] init];
NSCalendar* currentCalendar = [NSCalendar currentCalendar];
NSDateComponents* dateComponents = [currentCalendar components:NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitYear fromDate:today];
NSInteger thisMonth = [dateComponents month];
NSInteger thisDay = [dateComponents day];
NSInteger thisYear = [dateComponents year];
NSDateComponents* dayComponents = [[NSDateComponents alloc] init];
[dayComponents setDay:thisDay];
[dayComponents setMonth:thisMonth];
[dayComponents setYear:thisYear];
NSDate* todayAtMidnight = [currentCalendar dateFromComponents:dayComponents];
NSLog(#"Today at start of day:%#", todayAtMidnight);
Even if add
[dayComponents setHour:0]; the hour still comes out as 4.
What am I doing wrong?
To get the beginning of today you can use
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:[NSDate date]];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
NSLog(#"date %#", [calendar dateFromComponents:components]);
Make sure you have the correct timezone
2015-07-10 04:00:00 +0000 is UTC, not your local timezone.
To display it in your local timezone, use an NSDateFormatter:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd HH:mm";
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSLog([dateFormatter stringFromDate:todayAtMidnight]);
Use NSDateFormatter as follow because system timezone is UTC:
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate * curDate = [formatter dateFromString:[NSDate date]];
Then you'll get 2015-07-10 00:00:00.
I need to get the weekday of the first day of the month. For example, for the current month September 2013 the first day falls on Sunday.
At first, get the first day of current month (for example):
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit) fromDate:today];
components.day = 1;
NSDate *firstDayOfMonth = [gregorian dateFromComponents:components];
Then use NSDateFormatter to print it as a weekday:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEEE"];
NSLog(#"%#", [dateFormatter stringFromDate:firstDayOfMonth]);
P.S. also take a look at Date Format Patterns
Here is the solution to getting the weekday name of the first day in the current month
NSDateComponents *weekdayComps = [[NSDateComponents alloc] init];
weekdayComps = [calendar.currentCalendar components:calendar.unitFlags fromDate:calendar.today];
weekdayComps.day = 1;
NSDateFormatter *weekDayFormatter = [[NSDateFormatter alloc]init];
[weekDayFormatter setDateFormat:#"EEEE"];
NSString *firstweekday = [weekDayFormatter stringFromDate:[calendar.currentCalendar dateFromComponents:weekdayComps]];
NSLog(#"FIRST WEEKDAY: %#", firstweekday);
For the weekday index, use this
NSDate *weekDate = [calendar.currentCalendar dateFromComponents:weekdayComps];
NSDateComponents *components = [calendar.currentCalendar components: NSWeekdayCalendarUnit fromDate: weekDate];
NSUInteger weekdayIndex = [components weekday];
NSLog(#"WEEKDAY INDEX %i", weekdayIndex);
You can also increment or decrement the month if needed.
Depending on the output you need you may use NSDateFormatter (as it was already said) or you may use NSDateComponents class. NSDateFormatter will give you a string representation, NSDateComponents will give you integer values. Method weekday may do what you want.
NSDateComponents *components = ...;
NSInteger val = [components weekday];
For Swift 4.2
First:
extension Calendar {
func startOfMonth(_ date: Date) -> Date {
return self.date(from: self.dateComponents([.year, .month], from: date))!
}
}
Second:
self.firstWeekDay = calendar.component(.weekday, from: calendar.startOfMonth(Date()))
I'm struggling to figure out how to dynamically create a date object for the most previous sunday at 12:00 AM
I was thinking I could get today's date and then subtract the current day of the week + 1 at which point I could just subtract the time of the day do get down to 12AM.
so far I have the current day of the week:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
int weekday = [comps weekday];
at which point I can get today's date and subtract the difference of weekday * seconds in a day. However, how can I get today's time in seconds ??
No need to manually calculate seconds (which is dangerous anyway because of daylight saving etc.). The following should do exactly what you want:
NSDate *today = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en-US"]]; // force US locale, because other countries (e.g. the rest of the world) might use different weekday numbering
NSDateComponents *nowComponents = [calendar components:NSYearCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:today];
[nowComponents setWeekday:1]; //Sunday
[nowComponents setHour:0]; // 12:00 AM = midnight (12:00 PM would be 12)
[nowComponents setMinute:0];
[nowComponents setSecond:0];
NSDate *previousSunday = [calendar dateFromComponents:nowComponents];
I'll leave worrying about transitions between daylight savings time to you:
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [NSDate date];
NSLog(#"date %#", date);
NSDateComponents *componentsToday = [gregorian components:NSWeekdayCalendarUnit fromDate:date]; // NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit |
NSInteger days = componentsToday.weekday - 1;
NSLog(#"Days=%d", days);
NSDate *lastSunday = [date dateByAddingTimeInterval:-days*60*60*24];
NSLog(#"lastSunday %#", lastSunday);
NSDateComponents *componentsSunday = [gregorian components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:lastSunday];
[componentsSunday setHour:0];
[componentsSunday setMinute:0];
[componentsSunday setSecond:0];
NSDate *targetDate = [gregorian dateFromComponents:componentsSunday];
NSLog(#"TargetDate %#", targetDate);
#AndreasLey solution in Swift 2.0:
func getLastSunday() -> NSDate?
{
let today = NSDate();
let calendar : NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
calendar.locale = NSLocale(localeIdentifier: "en-US") // force US locale, because other countries (e.g. the rest of the world) might use different weekday numbering
let flags : NSCalendarUnit = [.Year , .Month, .Weekday, .WeekOfMonth, .Minute , .Second]
let nowComponents = calendar.components(flags, fromDate: today)
nowComponents.weekday = 1 //Sunday
nowComponents.hour = 0 // 12:00 AM = midnight (12:00 PM would be 12)
nowComponents.minute = 0
nowComponents.second = 0;
let previousSunday = calendar.dateFromComponents(nowComponents);
return previousSunday
}
This code is setting 12:00 am in your selected date from UIDatePicker.
NSDate *oldDateSelected = datePicker.date;
unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components:unitFlags fromDate:oldDateSelected];
comps.hour = 00;
comps.minute = 00;
comps.second = 44;
NSDate *newDate = [calendar dateFromComponents:comps];
return newDate;
I have two UIDatePicker controls in my app, one configured with UIDatePickerModeDate and one with UIDatePickerModeTime.
I want to configure a NSDate object with the date from UIDatePicker one and the time from the second one ... how?
Thanks,
Mark
Assume date1 and date2 are your two NSDate values. date1 contains your date components and date2 contains your time components. Here's how you would combine them together:
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// Extract date components into components1
NSDateComponents *components1 = [gregorianCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:date1];
// Extract time components into components2
NSDateComponents *components2 = [gregorianCalendar components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit
fromDate:date2];
// Combine date and time into components3
NSDateComponents *components3 = [[NSDateComponents alloc] init];
[components3 setYear:components1.year];
[components3 setMonth:components1.month];
[components3 setDay:components1.day];
[components3 setHour:components2.hour];
[components3 setMinute:components2.minute];
[components3 setSecond:components2.second];
// Generate a new NSDate from components3.
NSDate *combinedDate = [gregorianCalendar dateFromComponents:components3];
// combinedDate contains both your date and time!
For iOS 8.0 +
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
// Extract date components into components1
NSDateComponents *components1 = [gregorianCalendar components:(NSCalendarUnit)(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay)
fromDate:date1];
// Extract time components into components2
NSDateComponents *components2 = [gregorianCalendar components:(NSCalendarUnit)(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond)
fromDate:date2];
// Combine date and time into components3
NSDateComponents *components3 = [[NSDateComponents alloc] init];
[components3 setYear:components1.year];
[components3 setMonth:components1.month];
[components3 setDay:components1.day];
[components3 setHour:components2.hour];
[components3 setMinute:components2.minute];
[components3 setSecond:components2.second];
// Generate a new NSDate from components3.
NSDate * combinedDate = [gregorianCalendar dateFromComponents:components3];
// combinedDate contains both your date and time!
In Swift:
let calendar = NSCalendar.currentCalendar()
let date1 = NSDate() // PickerDateMode
let date2 = NSDate() // PickerHourMode
let componentsOne = calendar.components([.Year, .Month, .Day], fromDate: date1)
let componentsTwo = calendar.components([.Hour, .Minute], fromDate: date2)
let totalComponents = NSDateComponents()
totalComponents.year = componentsOne.year
totalComponents.month = componentsOne.month
totalComponents.day = componentsOne.day
totalComponents.hour = componentsTwo.hour
totalComponents.minute = componentsTwo.minute
let finalDate = calendar.dateFromComponents(totalComponents)
NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate *date = [NSDate date];//datapicker date
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];
NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];
NSInteger day = [dateComponents day];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];
Update to Swift 4 and 4.1
func combineDateAndTimeToOneDate() {
let datefrmter = DateFormatter()
datefrmter.dateFormat = "dd/MM/yyyy"
let dateFromString = datefrmter.date(from: lblDate.text!)
datefrmter.dateFormat = "h:mm a"
let timeFromString = datefrmter.date(from: lblTime.text!)
let calendar = NSCalendar.current
let componentsOne = calendar.dateComponents([.year,.month,.day], from: dateFromString!)
let componentsTwo = calendar.dateComponents([.hour,.minute,.second,.nanosecond], from: timeFromString!)
let totalComponents = NSDateComponents()
totalComponents.year = componentsOne.year!
totalComponents.month = componentsOne.month!
totalComponents.day = componentsOne.day!
totalComponents.hour = componentsTwo.hour!
totalComponents.minute = componentsTwo.minute!
totalComponents.second = componentsTwo.second!
totalComponents.nanosecond = componentsTwo.nanosecond!
let finalDate = calendar.date(from: totalComponents as DateComponents)
print(finalDate)
}
Hope it helps!
I have a calendar application in which I want to get the next year from the current date (NSDate).
How can I do this?
You can make NSDateComponents do all the hard work of calculating leap years and leap seconds:
NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setYear:1];
NSDate *nextYear = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];
As VdesmedT mentioned, you can use dateByAddingTimeInterval and add the seconds of one year. But to be more precise, you can do the following:
NSDate *today = [NSDate date]; // get the current date
NSCalendar* cal = [NSCalendar currentCalendar]; // get current calender
NSDateComponents* dateOnlyToday = [cal components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit ) fromDate:today];
[dateOnlyToday setYear:([dateOnlyToday year] + 1)];
NSDate *nextYear = [cal dateFromComponents:dateOnlyToday];
Hope this helps.
Swift 4:
let calendar = Calendar.current
let newDate = calendar.date(byAdding: .year, value: 1, to: Date())
This is my version: in swift.
let calendar = NSCalendar.currentCalendar()
let newDate = calendar.dateByAddingUnit(.Year, value: 1, toDate: NSDate(), options: NSCalendarOptions.MatchNextTime)