How to get day of month in number format? - objective-c

What I'm looking for is the day of the month, example 2, 5, 30 or 31. In integer form, and not a string. I'm not looking for a programmed date, but today's date in whatever local they are in.

All the above answers are bad ways to accomplish this. This is the right way:
NSDate *date = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSDayCalendarUnit fromDate:date];
NSInteger day = components.day;

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"d"];
NSInteger day = [[dateFormat stringFromDate:[NSDate date]] intValue];

Start with an NSDate then run it through an NSDateFormatter.
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html

Here is something that may work :
NSDate *theDate;
// Set theDate to the date you want
// For example, theDate = [NSDate date]; to get today's date
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"d";
NSString *theDayString = [formatter stringFromDate:theDate];
int theDay = theDayString.intValue;
NSLog (#"%d", theDay);
theDay contains the value you're looking for !

Related

How to convert Nstring to NSDate?

i want to convert nsstring to nsdate
i have string have this value
08:00:00
i want to convert it so i wrote this code
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
NSDate *startDate = [formatter dateFromString:_startTime];
NSLog(#"%#",startDate);
_startTime have this value = 08:00:00
but startDate after i display it , it had this value
2000-01-01 06:00:00 +0000
Update I wrote this code
NSString *dateString = _startTime;
NSDateFormatter *formatter= [[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
[formatter setDateFormat:#"HH:mm:ss"];
NSDate *startDate = [[NSDate alloc] init];
// voila!
startDate = [formatter dateFromString:dateString];
NSLog(#"%#",startDate);
i want the output be 08:00:00
You can't have NSDate without a date !
if you want to access the time from an NSDate you'll need to use NSDateComponents (or NSTimeInterval).
To access the time from your NSDate using NSDateComponents :
NSString *startTime = #"08:00:00";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
NSDate *startDate = [formatter dateFromString:startTime];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:startDate];
NSLog(#"%d:%d:%d", [components hour], [components minute], [components second]);
I don't get what's the purpose of changing the string _startTime, do you want to compare dates ?
Edit :
NSString *startTime = #"08:00:00";
NSString *endTime = #"23:00:00";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
NSDate *startDate = [formatter dateFromString:startTime];
NSDate *endDate = [formatter dateFromString:endTime];
NSTimeInterval difference = [endDate timeIntervalSinceDate:startDate];
NSInteger temp = difference;
NSDate* newDate = [[NSDate alloc] init];
for (int i = 0; (i < difference && [newDate compare:startDate] == NSOrderedDescending); ++i)
{
newDate = [startDate dateByAddingTimeInterval:(temp - i*60*10)];
NSLog(#"%#",newDate);
}
run this and use NSDateComponents to log what you want !
Use this code i think this one help you..
NSString *dateStr = #"08:00:00";
NSDateFormatter *datFormatter = [[NSDateFormatter alloc] init];
[datFormatter setDateFormat:#"HH:mm:ss"];
NSDate* mydate = [datFormatter dateFromString:dateStr];
NSLog(#"date: %#", [datFormatter stringFromDate:mydate]);
i think this is what you really want...

Return tomorrow's day name

I would like to return the weekday name of tomorrow (i.e. if today is Sunday, I want Monday). Here's my code that yields today's weekday name.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEEE"];
weekDay = [formatter stringFromDate:[NSDate date]];
Rather than messing with NSCalendar, what would be a concise way of doing this (following the code I have here)?
Thank you.
user's language aware:
NSDateFormatter * df = [[NSDateFormatter alloc] init];
NSArray *weekdays = [df weekdaySymbols];
NSDateComponents *c = [[NSDateComponents alloc] init];
c.day = 1;
NSDate *tomorrow = [[NSCalendar currentCalendar] dateByAddingComponents:c
toDate:[NSDate date]
options:0];
c = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit
fromDate:tomorrow];
NSString *tomorrowname = weekdays[c.weekday-1];// the value of c.weekday may
// range from 1 (sunday) to 7 (saturday)
NSLog(#"%#", tomorrowname);
if you need to have the name in a certain language, add
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"]];
after the creation of the date formatter.
Why are you afraid of "messing" with NSCalendar? For using the NSDateComponents methods, you will actually have to make use of NSCalendar. This is my solution for your problem.
// Get the current weekday
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
// !! Sunday = 1
NSInteger weekday = [weekdayComponents weekday];
Now, you can use the NSDateFormatter method -(NSArray *)weekdaySymbols which contains weekdays starting with Sunday at index 0. As the integer returned by [weekdayComponents weekday] starts with 0 for Saturday, we do not have to increase the value stored in weekday:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// !! Sunday = 0
NSUInteger symbolIndex = (weekday < 7) ? weekday : 0;
NSString *weekdaySymbol = [[formatter weekdaySymbols] objectAtIndex:(NSUInteger)symbolIndex];
I hope this was helpful although using NSCalendar to some extent.
EDIT: glektrik's solution is pretty straight ahead. But mind the following statement in the NSDate class reference of - dateByAddingTimeInterval:.
Return Value:
A new NSDate object that is set to seconds seconds relative to the receiver. The date returned might have a representation different from the receiver’s.
Thank you for your comment, Abizern. Here's what I did:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEEE"];
weekDay = [formatter stringFromDate:[NSDate date]];
NSDateComponents *tomorrowComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
NSDate *compDate = [[NSCalendar currentCalendar] dateFromComponents:tomorrowComponents];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
offsetComponents.day = 1;
NSDate *tomorrow = [[NSCalendar currentCalendar] dateByAddingComponents:offsetComponents toDate:compDate options:0];
nextWeekDay = [formatter stringFromDate:tomorrow];
Two NSString objects (weekDay and nextWeekDay) now store the days of the week names for today and tomorrow (currently Sunday and Monday).
This works well, but I wonder if there's an easier way. Objective-C dates are quite cumbersome :(
Thanks again.

Date Format as 2012-12-20T16:00:00.000Z?

I'm getting date as 2012-12-24 08:59:00 +0000 and i want it as 2012-12-20T16:00:00.000Z
i tried with this code
NSDateComponents *dayComponent = [[NSDateComponents alloc] init] ;
NSDate* now = [NSDate date];
NSCalendar *theCalendar = [NSCalendar currentCalendar];
NSDateFormatter* formatter = [NSDateFormatter alloc];
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZ"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
dayComponent.day = -2;
NSDate* fromDate = [theCalendar dateByAddingComponents:dayComponent toDate:now options:0];
fromDateStr = [formatter stringFromDate:fromDate];
my requirement is to get date of previous days like before 2 days, before 14 days etc in specified format.
but i'm getting fromDateStr as empty string.
Any suggestion would be appreciated.
The date format for 2012-12-20T16:00:00.000Z is
yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
Hope that helps.
Let me know if that does not give you the desired result.
Here is a sample code that worked for me:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSString *str = [formatter stringFromDate:[NSDate date]];
NSLog(#"Date = %#",str);
The output was:
Date = 2012-12-26T14:55:36.702Z

Convert date to next day's date in iOS

I have a date in string format just like 30-11-2012. I want the date next to it like 01-12-2012 again in string format.
Is there any way of getting it?
You should use NSCalendar for best compatibility
NSDate *today = [NSDate dateWithNaturalLanguageString:#"2011-11-30"];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dayComponent = [NSDateComponents new];
dayComponent.day = 1;
today = [calendar dateByAddingComponents:dayComponent toDate:today options:0];
//2011-12-01 12:00:00 +0000
I got the answer by someone I forget the name, I was about to accept his/her answer but when I clicked on accept answer it told me that the post bas been removed.
The answer given by that anonymous person was given below
NSString *dateString = #"22-11-2012";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
NSDateComponents *components= [[NSDateComponents alloc] init];
[components setDay:1];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *dateIncremented= [calendar dateByAddingComponents:components toDate:dateFromString options:0];
NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
[myDateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *stringFromDate = [myDateFormatter stringFromDate:dateIncremented];
NSLog(#"%#", stringFromDate);
In the end I really like to thanks that anonymous person, I know this was not as much tricky but this helped me a lot. Thanks again you the Anonymous Helper.
swift 3.0
var components = DateComponents()
components.day = 1
let now = Date()
let futureDate = Calendar.current.date(byAdding: components, to: now, wrappingComponents: false)
//now = 2017-03-22 futureDate = 2017-03-23

How to convert to next day when currents date format is "MMM dd, yyyy hh:mm:ss a"?

I have a date in my application which has this format :
"MMM dd, yyyy hh:mm:ss a"
The user chooses a day from a picker and the date is always converted to this format. From this format how can i get the date after exactly 24 hours?
For example if the date is Mon 24 , 2012 17:44:33 i need the code to transform it to Tue 25 , 2012 17:44:33.
Read the Date and Time Programming Guide.
Use a date formatter to generate a date from the string.
Add one day to the date.
Use a date formatter to generate a string from your new date.
Use the following code to create a NSDate from your string:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setCalendar:[NSCalendar currentCalendar]];
[dateFormatter setDateFormat:<FORMAT_OF_DATE_STRING>];
NSDate *date = [dateFormatter dateFromString:<DATE_STRING>];
[dateFormatter release];
Use the following code to add days to a NSDate:
NSDate *today =<YOUR_DATE>
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
/*
Create a date components to represent the number of days to add to the current date.
The weekday value for Sunday in the Gregorian calendar is 1, so add 1 from the number of days to subtract from the date in question. (If today is Sunday, add 0 days.)
*/
NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
if(day<7)
{
[componentsToAdd setDay: day];
}
NSDate *calculateDay = [gregorian dateByAddingComponents:componentsToAdd
toDate:today options:0];
Happy coding!
Here is the code you need to set up the date formatter:
NSString *dateString = #"Tue 24 , 2012 17:44:33";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"EEE dd , yyyy HH:mm:ss"];
NSDate *theDate = [dateFormat dateFromString:dateString];
theDate = [NSDate dateWithTimeInterval:(60*60*24) sinceDate:theDate];
NSString *newDate = [dateFormat stringFromDate:theDate];
NSLog(#"%#",newDate);
The console returns:
2012-07-18 09:26:28.395 TesterProject[71645:f803] Wed 25 , 2012 17:44:33
You really should include a month though, because it will just take the current month if you do not, and that can throw off your day of the week.
I used the actual format of the dates you entered, not the incorrect format that you typed in your question. For information on date formatting here is the unicode standards.
For information on NSDateFormatter here is the Apple documentation: NSDateFormatter.
EDIT: Here is an alternate implementation:
NSString *dateString = #"Tue 24 , 2012 17:44:33";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"EEE dd , yyyy HH:mm:ss"];
NSDate *theDate = [dateFormat dateFromString:dateString];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:1];
theDate = [gregorian dateByAddingComponents:offsetComponents toDate:theDate options:0];
NSString *newDate = [dateFormat stringFromDate:theDate];
NSLog(#"%#",newDate);
It returns the exact same thing.