Trying to use NSDate for time only - ios

I'm struggling to find a way to use NSDate for time only purposes.
I was trying to do the following code:
- (void)awakeFromInsert
{
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.minute = 45;
comps.second = 0;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
self.periodDuration = [calendar dateFromComponents:comps];
NSLog(#"periodDuration: %#",self.periodDuration);
comps = [[NSDateComponents alloc] init];
comps.hour = 8;
comps.minute = 0;
self.firstPeriodStartTime = [calendar dateFromComponents:comps];
NSLog(#"firstPeriodTime: %#",self.periodDuration);
}
But the result I get is:
periodDuration: 0001-12-31 22:24:04 +0000
firstPeriodTime: 0001-12-31 22:24:04 +0000
The result I was expecting:
periodDuration: 45:00
firstPeriodTime: 08:00
What am I doing wrong? How can I fix this?
Thank you.

The log of date is misleading you, if you are forming a date with only a few components you will not get a proper date instance which uniquely identifies a date and time.
If you try with this code snipped you can find that if you are just converting the dates back to string it is just as you expect
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.minute = 45;
comps.second = 0;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *periodDate = [calendar dateFromComponents:comps];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"mm:ss"];
NSLog(#"periodDuration: %#",[dateFormatter stringFromDate:periodDate]);
comps = [[NSDateComponents alloc] init];
comps.hour = 8;
comps.minute = 0;
NSDate *firstPeriodDate = [calendar dateFromComponents:comps];
[dateFormatter setDateFormat:#"HH:mm"];
NSLog(#"firstPeriodTime: %#",[dateFormatter stringFromDate:firstPeriodDate]);
periodDuration: 45:00
firstPeriodTime: 08:00

You can use NSDateFormatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm"];
NSLog(#"%#",[dateFormatter stringFromDate:[NSDate date]]);

Use a NSTimeInterval (which is, basically, a double containing the number of seconds). To store it in CoreData:
[NSNumber numberWithDouble:myTimeInterval];
As for formatting: If you want more than 24h displayed, use this:
NSUInteger seconds = (NSUInteger)round(myTimeInterval);
NSString *formattedDate = [NSString stringWithFormat:#"%02u:%02u:%02u",
seconds / 3600, (seconds / 60) % 60, seconds % 60];
NSLog(#"%#", formattedDate);
If you don't want more than 24h, you can use NSDate and NSDateFormatter again:
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:myTimeInterval];
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
NSString *formattedDate = [dateFormatter stringFromDate:date];
NSLog(#"%#", formattedDate);

NSString *timeString;
timeString = [NSDateFormatter localizedStringFromDate:[NSDate date]
dateStyle:NSDateFormatterNoStyle
timeStyle:NSDateFormatterMediumStyle];
12:03:54 PM

Related

Convert NSSting to NSDate

I have string 2015-08-10T12:00 how can I convert it to Date?
My code did not works
[self.dataFormatter setDateFormat:#"yyyy-MM-ddTHH:mm"];
NSDate *date = [self.dataFormatter dateFromString:dateStg];
Use this date format:
yyyy-MM-dd'T'HH:mm
converted current Date into String
//Get Current Date
NSLocale *en_US_POSIX = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
assert(en_US_POSIX != nil);
NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:en_US_POSIX];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *resultString = [dateFormatter stringFromDate: currentTime];
Converted Current Time inTo NSString
//Get Current Date
NSDate* now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *dateComponents = [gregorian components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:now];
NSInteger hour = [dateComponents hour];
NSString *am_OR_pm=#"AM";
if (hour>12){
hour=hour%12;
am_OR_pm = #"PM";
}
NSInteger minute = [dateComponents minute];
NSString *strTime=[NSString stringWithFormat:#"%02d:%02d %#", hour, minute ,am_OR_pm];
Converted NSString to NSDate
NSString *dateString = #"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];

how to find out what day is a date in iOS [duplicate]

I have a webservice that returns the date in this format:
2013-04-14
How do i figure out what day this corresponds to?
This code will take your string, convert it to an NSDate object and extract both the number of the day (14) and the name of the day (Sunday)
NSString *myDateString = #"2013-04-14";
// Convert the string to NSDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd";
NSDate *date = [dateFormatter dateFromString:myDateString];
// Extract the day number (14)
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:date];
NSInteger day = [components day];
// Extract the day name (Sunday)
dateFormatter.dateFormat = #"EEEE";
NSString *dayName = [dateFormatter stringFromDate:date];
// Print
NSLog(#"Day: %d: Name: %#", day, dayName);
Note: This code is for ARC. If MRC, add [dateFormatter release] at the end.
An alternate method for getting the weekday can be:
NSString *myDateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:myDateString];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:date];
NSInteger weekday = [components weekday];
NSString *weekdayName = [dateFormatter weekdaySymbols][weekday - 1];
NSLog(#"%# is a %#", myDateString, weekdayName);
You can use this code it working for me.
NSString *dateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter setDateFormat:#"EEEE"];
NSLog(#"%#", [dateFormatter stringFromDate:dateFromString]);
If you have 2013-04-14 stored in a NSString called date, then you can do this...
NSArray *dateComponents = [date componentsSeperatedByString:#"-"];
NSString *day = [dateComponents lastObject];
Swift 3:
let datFromat = DateFormatter()
datFormat.dateFormat = "EEEE"
let name = datFormat.string(from: Date())
Bonus: If you want to set your own date template instead of using Date() above:
let datFormat = DateFormatter()
datFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let thisDate = datFormat.date(from: "2016-10-13T18:00:00-0400")
Then call the 1st code after this.

Add 3 Hours to an NSDate's Hour

I want to add 3 hours to my current date. I am using the following code to add hours but it adds 6 hours to the current date.
NSDate *n = [NSDate date];
int daysToAdd = 3; // or 60 :-)
// set up date components
NSDateComponents *components1 = [[[NSDateComponents alloc] init] autorelease];
[components1 setHour:daysToAdd];
// create a calendar
NSCalendar *gregorian12 = [NSCalendar currentCalendar];
NSDate *newDate2 = [gregorian12 dateByAddingComponents:components toDate:n options:0];
NSLog(#"Clean: %#", newDate2);
Result is :-
2013-09-10 12:25:24.752 project[1554:c07] Clean: 2013-09-10 06:55:15 +0000
Try this
NSString *strCurrentDate;
NSString *strNewDate;
NSDate *date = [NSDate date];
NSDateFormatter *df =[[NSDateFormatter alloc]init];
[df setDateStyle:NSDateFormatterMediumStyle];
[df setTimeStyle:NSDateFormatterMediumStyle];
strCurrentDate = [df stringFromDate:date];
NSLog(#"Current Date and Time: %#",strCurrentDate);
int hoursToAdd = 3;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setHour:hoursToAdd];
NSDate *newDate= [calendar dateByAddingComponents:components toDate:date options:0];
[df setDateStyle:NSDateFormatterMediumStyle];
[df setTimeStyle:NSDateFormatterMediumStyle];
strNewDate = [df stringFromDate:newDate];
NSLog(#"New Date and Time: %#",strNewDate);
Output
Current Date and Time: Sep 10, 2013, 1:15:41 PM
New Date and Time: Sep 10, 2013, 4:15:41 PM
NSDate *CurrentTimedate = [NSDate date];
NSLog(#"%#",CurrentTimedate);
NSDate *newDate = [CurrentTimedate dateByAddingTimeInterval:60*60*3];
NSLog(#"%#",newDate);
NSDate *newDate = [oldDate dateByAddingTimeInterval:hrs*60*60];

How do I take a date and extract the day in iOS"

I have a webservice that returns the date in this format:
2013-04-14
How do i figure out what day this corresponds to?
This code will take your string, convert it to an NSDate object and extract both the number of the day (14) and the name of the day (Sunday)
NSString *myDateString = #"2013-04-14";
// Convert the string to NSDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd";
NSDate *date = [dateFormatter dateFromString:myDateString];
// Extract the day number (14)
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:date];
NSInteger day = [components day];
// Extract the day name (Sunday)
dateFormatter.dateFormat = #"EEEE";
NSString *dayName = [dateFormatter stringFromDate:date];
// Print
NSLog(#"Day: %d: Name: %#", day, dayName);
Note: This code is for ARC. If MRC, add [dateFormatter release] at the end.
An alternate method for getting the weekday can be:
NSString *myDateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:myDateString];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:date];
NSInteger weekday = [components weekday];
NSString *weekdayName = [dateFormatter weekdaySymbols][weekday - 1];
NSLog(#"%# is a %#", myDateString, weekdayName);
You can use this code it working for me.
NSString *dateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter setDateFormat:#"EEEE"];
NSLog(#"%#", [dateFormatter stringFromDate:dateFromString]);
If you have 2013-04-14 stored in a NSString called date, then you can do this...
NSArray *dateComponents = [date componentsSeperatedByString:#"-"];
NSString *day = [dateComponents lastObject];
Swift 3:
let datFromat = DateFormatter()
datFormat.dateFormat = "EEEE"
let name = datFormat.string(from: Date())
Bonus: If you want to set your own date template instead of using Date() above:
let datFormat = DateFormatter()
datFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let thisDate = datFormat.date(from: "2016-10-13T18:00:00-0400")
Then call the 1st code after this.

find total number of days between two dates in iphone

I would like to find total number of days between two dates.
e.g. today is 01-01-2011(DD-MM-YYYY) and second date is (25-03-2011), how would I find the total number of days?
NSDate *currentdate=[NSDate date];
NSLog(#"curretdate is ==%#",currentdate);
NSDateFormatter *tempFormatter1 = [[[NSDateFormatter alloc]init]autorelease];
[tempFormatter1 setDateFormat:#"dd-mm-YYYY hh:mm:ss"];
NSDate *toDate = [tempFormatter1 dateFromString:#"20-04-2011 09:00:00"];
NSLog(#"toDate ==%#",toDate);
In your date Format tor u set wrong it`s be dd-MM-yyyy HH:mm:ss . may be that was the problem.. u get wrong date and not get answer i send litte bit code for get day diffrence.
NSDateFormatter *tempFormatter = [[[NSDateFormatter alloc]init]autorelease];
[tempFormatter setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
NSDate *startdate = [tempFormatter dateFromString:#"15-01-2011 09:00:00"];
NSLog(#"startdate ==%#",startdate);
NSDateFormatter *tempFormatter1 = [[[NSDateFormatter alloc]init]autorelease];
[tempFormatter1 setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
NSDate *toDate = [tempFormatter1 dateFromString:#"20-01-2011 09:00:00"];
NSLog(#"toDate ==%#",toDate);
int i = [startdate timeIntervalSince1970];
int j = [toDate timeIntervalSince1970];
double X = j-i;
int days=(int)((double)X/(3600.0*24.00));
NSLog(#"Total Days Between::%d",days);
Edit 1:
we can find date difference using following function :
-(int)dateDiffrenceFromDate:(NSString *)date1 second:(NSString *)date2 {
// Manage Date Formation same for both dates
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd-MM-yyyy"];
NSDate *startDate = [formatter dateFromString:date1];
NSDate *endDate = [formatter dateFromString:date2];
unsigned flags = NSDayCalendarUnit;
NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];
int dayDiff = [difference day];
return dayDiff;
}
from Abizern`s ans. find more infromation for NSDateComponent here.
NSCalendar *Calander = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[dateFormat setDateFormat:#"dd"];
[comps setDay:[[dateFormat stringFromDate:[NSDate date]] intValue]];
[dateFormat setDateFormat:#"MM"];
[comps setMonth:[[dateFormat stringFromDate:[NSDate date]] intValue]];
[dateFormat setDateFormat:#"yyyy"];
[comps setYear:[[dateFormat stringFromDate:[NSDate date]] intValue]];
[dateFormat setDateFormat:#"HH"];
[comps setHour:05];
[dateFormat setDateFormat:#"mm"];
[comps setMinute:30];
NSDate *currentDate=[Calander dateFromComponents:comps];
NSLog(#"Current Date is :- '%#'",currentDate);
[dateFormat setDateFormat:#"dd"];
[comps setDay:[[dateFormat stringFromDate:yourDate] intValue]];
[dateFormat setDateFormat:#"MM"];
[comps setMonth:[[dateFormat stringFromDate:yourDate] intValue]];
[dateFormat setDateFormat:#"yyyy"];
[comps setYear:[[dateFormat stringFromDate:yourDate] intValue]];
[dateFormat setDateFormat:#"HH"];
[comps setHour:05];
[dateFormat setDateFormat:#"mm"];
[comps setMinute:30];
NSDate *reminderDate=[Calander dateFromComponents:comps];
//NSLog(#"Current Date is :- '%#'",reminderDate);
//NSLog(#"Current Date is :- '%#'",currentDate);
NSTimeInterval ti = [reminderDate timeIntervalSinceDate:currentDate];
//NSLog(#"Time Interval is :- '%f'",ti);
int days = ti/86400;
[dateFormat release];
[Calander release];
[comps release];
Hope It will work for you........
A simpler way of doing it is:
// This just sets up the two dates you want to compare
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"dd-MM-yyyy"];
NSDate *startDate = [formatter dateFromString:#"01-01-2011"];
NSDate *endDate = [formatter dateFromString:#"25-03-2011"];
// This performs the difference calculation
unsigned flags = NSDayCalendarUnit;
NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];
// This just logs your output
NSLog(#"Start Date, %#", startDate);
NSLog(#"End Date, %#", endDate);
NSLog(#"%ld", [difference day]);
And the results are:
Start Date, 2011-01-01 00:00:00 +0000
End Date, 2011-03-25 00:00:00 +0000
83
Trying to use and manipulate seconds for calculating time differences is a bad idea. There are a whole load of classes and methods provided by Cocoa for Calendrical calculations and you should use them as much as possible.
Try this
- (int) daysToDate:(NSDate*) endDate
{
//dates needed to be reset to represent only yyyy-mm-dd to get correct number of days between two days.
NSDateFormatter *temp = [[NSDateFormatter alloc] init];
[temp setDateFormat:#"yyyy-MM-dd"];
NSDate *stDt = [temp dateFromString:[temp stringFromDate:self]];
NSDate *endDt = [temp dateFromString:[temp stringFromDate:endDate]];
[temp release];
unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:stDt toDate:endDt options:0];
int days = [comps day];
[gregorian release];
return days;
}
//try it
if((![txtFromDate.text isEqualToString:#""]) && (![txtToDate.text isEqualToString:#""]))
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM/dd/yyyy"];
NSDate *startDate = [formatter dateFromString:txtFromDate.text];
NSDate *endDate = [formatter dateFromString:txtToDate.text];
unsigned flags = NSDayCalendarUnit;
NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];
int dayDiff = [difference day];
lblNoOfDays.text =[NSString stringWithFormat:#"%d",dayDiff];
}
to find the number of dates between start date to end date.
NSCalendar *cale=[[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
unsigned unitFlags=NSMonthCalendarUnit| NSDayCalendarUnit;
NSDateComponents *comp1=[cale components:unitFlags fromDate:startDate toDate:endDate options:0];
NSInteger days=[comp1 day];
NSLog(#"Days %ld",(long)days);
NSDate *dateA;
NSDate *dateB;
NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
fromDate:dateA
toDate:dateB
options:0];
NSLog(#"Difference in date components: %i/%i/%i", components.day, components.month, components.year);
//write this code in .h file
{
NSDate *startDate,*EndDate;
NSDateFormatter *Date_Formatter;
}
//write this code in .h file`enter code here`
- (void)viewDidLoad
{
[super viewDidLoad];
Date_Formatter =[[NSDateFormatter alloc]init];
[Date_Formatter setDateFormat:#"dd-MM-yyyy"];
UIToolbar *numbertoolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
numbertoolbar.barStyle = UIBarStyleBlackTranslucent;
numbertoolbar.items = [NSArray arrayWithObjects:[[UIBarButtonItem alloc]initWithTitle:#"Next"
style:UIBarButtonItemStyleDone target:self action:#selector(doneWithNumberPad)],nil];
[numbertoolbar sizeToFit];
Txt_Start_Date.inputAccessoryView = numbertoolbar;
[Txt_Start_Date setInputView:Picker_Date];
Txt_End_Date.inputAccessoryView = numbertoolbar;
[Txt_End_Date setInputView:Picker_Date];
[Picker_Date addTarget:self action:#selector(updateTextfield:) forControlEvents:UIControlEventValueChanged];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)doneWithNumberPad
{
if ([Txt_Start_Date isFirstResponder])
{
[Txt_Start_Date resignFirstResponder];
[Txt_End_Date becomeFirstResponder];
}
else if([Txt_End_Date isFirstResponder])
{
[Txt_End_Date resignFirstResponder];
startDate =[Date_Formatter dateFromString:Txt_Start_Date.text];
EndDate =[Date_Formatter dateFromString:Txt_End_Date.text];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSDayCalendarUnit fromDate:startDate toDate:EndDate options:0];
Lab_Total_Days.text =[NSString stringWithFormat:#"%ld",components.day];
}
}
Please try this. Hope it helps you...
NSDateFormatter *df=[[NSDateFormatter alloc] init];
// Set the date format according to your needs
[df setDateFormat:#"MM/dd/YYYY hh:mm a"]; //for 12 hour format
//[df setDateFormat:#"MM/dd/YYYY HH:mm "] // for 24 hour format
NSDate *date1 = [df dateFromString:firstDateString];
NSDate *date2 = [df dateFromString:secondDatestring];
NSLog(#"%#f is the time difference",[date2 timeIntervalSinceDate:date1]);
[df release];

Resources