I want to show the date as per Local format of different country.
I got the code from here: Get the user's date format? (DMY, MDY, YMD)
NSString *base = #"MM/dd/yyyy";
NSLocale *locale = [NSLocale currentLocale];
NSString *format = [NSDateFormatter dateFormatFromTemplate:base options:0 locale:locale];
But how can I fetch the order of dd,mm,yyyy from the format?
This will get you the format of the currentLocale:
NSString *dateComponents = #"ddMMyyyy";
NSLocale *locale = [NSLocale currentLocale];
NSString* format = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:locale];
To print a NSDate object in the right format for the currentLocale try this:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [NSLocale currentLocale];
[dateFormatter setLocale:locale];
NSString *dateComponents = #"ddMMyyyy";
NSString* format = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:locale];
NSDate* date = [NSDate date];
[dateFormatter setDateFormat:format];
NSString *newDateString = [dateFormatter stringFromDate:date];
NSLog(#"Current date for locale: %#", newDateString);
If you really want the number-order of the dd, MM and yyyy elements it can be done like the following code. It is not(!) pretty and I really think you should reconsider if it is necessary to get the order of the elements.
NSString *dateComponents = #"ddMMyyyy";
NSLocale *locale = [NSLocale currentLocale];
NSString* format = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:locale];
int currentOrder = -1;
int nextIndex = 0;
int dd = -1;
int MM = -1;
int yyyy = -1;
NSString* workingSubstring;
while (dd == -1 || MM == -1 || yyyy == -1)
{
workingSubstring = [[format substringFromIndex:nextIndex] substringToIndex:2];
if ([workingSubstring isEqualToString:#"dd"])
{
dd = ++currentOrder;
nextIndex += 3;
}
else if ([workingSubstring isEqualToString:#"MM"])
{
MM = ++currentOrder;
nextIndex += 3;
}
else if ([workingSubstring isEqualToString:#"yy"])
{
yyyy = ++currentOrder;
nextIndex += 5;
}
}
NSLog(#"dd: %d, MM: %d, yyyy: %d", dd, MM, yyyy);
Related
I have an array containing birth dates like the one below:
Array(
"11/07/2013",
"07/10/2013",
"20/02/2013"
)
Now I want to make a new array based on whether or not the date has passed. Writing this question in 2013, if a current date has passed then we will change that date's year to 2014. If it hasn't passed then we will have it stay the 2013 date.
For example:
NewArray(
"11/07/2013", no change cus this date hasnt passed yet
"07/10/2013", no change same as above
"20/02/2014" **as date has already passed thats why 2014**
I'm using the following code for this
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
NSString *curYear = [dateFormatter stringFromDate:[NSDate date]];
NSString *nextYear = [NSString stringWithFormat: #"%d", ([curYear intValue] + 1)];
for(int i = 0; i < [_newlymadeArray count]; i++)
{
NSString *dateStr = [_newlymadeArray objectAtIndex:i];
NSComparisonResult comResult = [[dateFormatter dateFromString:dateStr] compare: [NSDate date]];
if(comResult == NSOrderedAscending)
{
[dateStr stringByReplacingOccurrencesOfString:curYear withString:nextYear];
[_newlymadeArray replaceObjectAtIndex:i withObject:dateStr];
NSLog(#"_newlymadeArray%#",_newlymadeArray);
}
NSLog(#"_newlymadeArray%#",_newlymadeArray);
This is however what I get when I NSLog _newlymadeArray:
after replacing (
"11/07/2013",
"07/10/2013",
"20/02/2013"
)
At index 2 it should be "20/02/2014" instead of the 2013 date. What might cause my problem and how can I solve it?
I've made some modifications to your code, and it is working as you want.
In my code I've compared date, which is in Ascending form of current date. If it satisfies the condition, then I've fetched YEAR from matched date, by the DateFormatter "yyyy". Then I simply increment this year by 1, and replace this year in old Date, which is "20/02/2013" to "20/02/2014"
array = [[NSMutableArray alloc] initWithObjects:#"11/07/2013",#"07/10/2013",#"20/02/2013", nil];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
for(int i = 0; i < [array count]; i++)
{
NSString *dateStr = [array objectAtIndex:i];
NSComparisonResult comResult = [[dateFormatter dateFromString:dateStr] compare: [NSDate date]];
if(comResult == NSOrderedAscending)
{
NSDateFormatter *yrFormatter = [[NSDateFormatter alloc] init];
[yrFormatter setDateFormat:#"yyyy"];
NSString *curYear = [yrFormatter stringFromDate:[NSDate date]];
NSString *nextYear = [NSString stringWithFormat: #"%d", ([curYear intValue] + 1)];
NSLog(#"%#",curYear);
NSLog(#"%#",nextYear);
dateStr = [dateStr stringByReplacingOccurrencesOfString:curYear withString:nextYear];
NSLog(#"%#",dateStr);
[array replaceObjectAtIndex:i withObject:dateStr];
NSLog(#"_newlymadeArray%#",array);
}
NSLog(#"_newlymadeArray%#",array);
}
This seems to be working perfectly, so I hope it helps you.
Plese dear try to use this one.I think this one may help
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents* components = [[NSDateComponents alloc] init];
components.year = 1;
NSDate* newDate = [calendar dateByAddingComponents: components toDate:#"YourDate" options: 0];
Otherwise you can use this one code.
if (comResult == NSOrderedSame)
{
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents* components = [[NSDateComponents alloc] init];
components.year = 1;
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"dd/MM/yyyy"];
NSDate *date = [formatter dateFromString:#"11/07/2013"];
NSDate* newDate = [calendar dateByAddingComponents: components toDate:date options: 0];
// here replace your array object with this "newDate"
}
Compare your array date to today's date with NSDate compare function. Here are the details:
NSString *arrayDateString = #"20/02/2013" // fetch this string from your array
NSDate *todaysDate = [NSDate date];
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd/MM/yyyy"];
NSDate* d = [df dateFromString:arrayDateString];
// now compare this date (d) with todaysDate using NSDate function
if ([d compare:todaysdate]== NSOrderedAscending)
{//write your code here}
If it results NSOrderedAscending, then it means array date is earlier than today's date.
So for that date, update year incremented by one using NSDateComponents:
NSDateComponents *dayComponent = [[[NSDateComponents alloc] init] autorelease];
dayComponent.year = 1;
NSCalendar *theCalendar = [NSCalendar currentCalendar];
dateToBeIncremented = [theCalendar dateByAddingComponents:dayComponent toDate:dateToBeIncremented options:0];
Or you can use NSDate function itself:
NSDate *now = arrayDate;
int yearsToAdd = 1;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*365*year];
But second option is not full-proof - because of leap year problem.
Hope this two options help you, for solving your issue.
NSArray * array = [[NSArray alloc] initWithObjects:#"11/07/2013",#"07/10/2013",#"20/02/2013", nil];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
NSMutableArray *output = [NSMutableArray new];
for(int i = 0; i < [array count]; i++)
{
NSString *dateStr = [array objectAtIndex:i];
NSDate *date = [dateFormatter dateFromString:dateStr];
if ([date compare:now] == NSOrderedAscending)
{
[components setYear:1];
date = [calendar dateByAddingComponents:components toDate:date options:0];
}
dateStr = [dateFormatter stringFromDate:date];
[output addObject:dateStr];
}
NSLog(#"Result : %#",output);
I have this ticks value "634758517020305000" which corresponds to 21st June 2012. I tried to convert the tick value into NSDate object like this:
NSString *str = #"634758517020305000";
NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
NSDate *date = [[NSDate dateWithTimeIntervalSince1970:
[[str substringWithRange:NSMakeRange(0, [str length])] intValue]]
dateByAddingTimeInterval:offset];
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSString *fourDigitYearFormat = [[dateFormatter dateFormat] stringByReplacingOccurrencesOfString:#"yy" withString:#"yyyy"];
[dateFormatter setDateFormat:fourDigitYearFormat];
}
// There you have it:
NSString *outputString = [dateFormatter stringFromDate:date];
But I got the output: 1/19/2038. If anyone knows where I am doing wrong, please let me know.
your Unix timestamps is wrong. it should be 1340236800
check your Unix timestamps Here
I need to check an event date, which should be between Current date and 60 days from now. The below code is used, but it is NOT working correctly. Please note, i'm getting event string like this - "2012-04-14T16:50:02Z" from my server.
// current date
double currDateInMilliSecs = [NSDate timeIntervalSinceReferenceDate] * 1000;
NSLog(#"currDateInMilliSecs: %f", currDateInMilliSecs);
// sixty days
double sixtydaysvalue = 60.0 * 24.0 * 3600.0 * 1000.0;
NSLog(#"sixtydaysvalue: %f", sixtydaysvalue);
// add current date + sixt days
double sixtyDaysMilliSecsFromCurrDate = currDateInMilliSecs + sixtydaysvalue;
NSLog(#"sixtyDaysMilliSecsFromCurrDate: %f", sixtyDaysMilliSecsFromCurrDate);
// check does the event date between current date + 60 days
NSDateFormatter *df = [[NSDateFormatter alloc] init];
//[df setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[df setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
//[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
// [eventDict objectForKey:#"begin_at"] gives date string like this "2012-04-14T16:50:02Z" for ex.
NSDate *eventdate = [df dateFromString:[eventDict objectForKey:#"begin_at"]];
NSTimeInterval nowSinceEventDate = [eventdate timeIntervalSince1970];
NSLog(#"nowSinceEventDate: %f", nowSinceEventDate);
double eventDateInMilliSecs = nowSinceEventDate * 1000;
NSLog(#"eventDateInMilliSecs: %f", eventDateInMilliSecs);
// this is not working as expected
if ( eventDateInMilliSecs<sixtyDaysMilliSecsFromCurrDate && eventDateInMilliSecs>currDateInMilliSecs )
{
}
else
{
}
Any help please?
try this
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss SSS"];
Try this:
NSString *dateString = #"2012-04-14T16:50:02Z";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *eventDate = [formatter dateFromString:dateString];
NSTimeInterval nowSinceEventDate = [eventDate timeIntervalSince1970];
NSLog(#"interval = %f", nowSinceEventDate);
UPDATE:
NSString *dateString = #"2012-05-21T16:50:02Z";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *eventDate = [formatter dateFromString:dateString];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:60];
NSDate *minDate = [NSDate date];
NSDate *maxDate = [gregorian dateByAddingComponents:components toDate:minDate options:0];
NSLog(#"eventDate interval = %f", [eventDate timeIntervalSince1970]);
NSLog(#"minDate interval = %f", [minDate timeIntervalSince1970]);
NSLog(#"maxDate interval = %f", [maxDate timeIntervalSince1970]);
BOOL isBetween = (([eventDate compare:minDate] == NSOrderedDescending) && ([eventDate compare:maxDate] == NSOrderedAscending));
NSLog(#"isBetween = %d", isBetween);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss:SSS"];
// [eventDict objectForKey:#"begin_at"] gives "2012-04-14T16:50:02Z"
NSDate *eventdate = [df dateFromString:[eventDict objectForKey:#"begin_at"]];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
SSS for milli seconds
I am trying to convert my date from NSString to NSDate using following code
NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
[dateformatter setDateStyle:NSDateFormatterShortStyle];
[dateformatter setTimeStyle:NSDateFormatterNoStyle];
[dateformatter setDateFormat:#"dd/MM/yyyy"];
NSDate *myDate = [[NSDate alloc] init];
currMonth = 3;
currYear = 2012;
NSString *str = [NSString stringWithFormat:#"01/%2d/%d", currMonth, currYear];
str = [str stringByReplacingOccurrencesOfString:#" " withString:#"0"];
myDate = [dateformatter dateFromString:str];
NSLog(#"myStr: %#",str);
NSLog(#"myMonth: %2d",currMonth);
NSLog(#"myYear: %d",currYear);
NSLog(#"myDate: %#",myDate);
Above code is giving me wrong date. Can anyone please help?
What is your output? Keep in mind, that NSDate is in UTC.
2012-03-01 00:00:00 (GMT+1) is 2012-02-39 23:00:00 (UTC)
Another tip:
%02 formats your integers with leading zeros.
Try this:
-(NSDate *)dateFromString:(NSString *)string
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormat setLocale:locale];
[dateFormat setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSTimeInterval interval = 5 * 60 * 60;
NSDate *date1 = [dateFormat dateFromString:string];
date1 = [date1 dateByAddingTimeInterval:interval];
if(!date1) date1= [NSDate date];
[dateFormat release];
[locale release];
return date1;
}
Tell me if it helps u :]
try
NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
[dateformatter setDateStyle:NSDateFormatterShortStyle];
[dateformatter setTimeStyle:NSDateFormatterNoStyle];
[dateformatter setDateFormat:#"dd/MM/yyyy"];
NSDate *myDate = [[NSDate alloc] init];
int currMonth = 3;
int currYear = 2012;
NSString *str = [NSString stringWithFormat:#"01/%2d/%d", currMonth, currYear];
str = [str stringByReplacingOccurrencesOfString:#" " withString:#"0"];
//SET YOUT TIMEZONE HERE
dateformatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"PDT"];
myDate = [dateformatter dateFromString:str];
NSLog(#"myStr: %#",str);
NSLog(#"myMonth: %2d",currMonth);
NSLog(#"myYear: %d",currYear);
NSLog(#"myDate: %#",myDate);
I have a String with a datetime format: "YYYY-MM-DD HH:MM:SS".
I use this in my source code:
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"%e. %B %Y"];
NSString *test = [formatter stringFromDate:#"2010-01-10 13:55:15"];
I want to convert from "2010-01-10 13:55:15" to "10. January 2010".
But my implementation does not work.
What's wrong here?
Thanks a lot in advance & Best Regards.
Updated source code:
[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"%Y-%m-%d %H:%M:%S"];
NSString *test1 = [formatter stringFromDate:#"2010-01-10 13:55:15"];
NSDateFormatter *formatter1 = [[[NSDateFormatter alloc] init] autorelease];
[formatter1 setDateFormat:#"%d. %M4 %Y"];
NSString *test2 = [formatter1 stringFromDate:test1];
A date formatter can only handle one format at a time. You need to take this approach:
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [f dateFromString:#"2010-01-10 13:55:15"];
NSDateFormatter *f2 = [[NSDateFormatter alloc] init];
[f2 setDateFormat:#"d. MMMM YYYY"];
NSString *s = [f2 stringFromDate:date];
s will now be "10. January 2010"
Here are a few examples of working with data formatters from my code. You should be able to take any one of these functions and tweak it for your format.
USAGE
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [Constants getTitleDateFormatter];
NSString *dateString = [dateFormatter stringFromDate:today];
[dateFormatter release];
FUNCTIONS
+ (NSDateFormatter *) getDateFormatterWithTimeZone {
//Returns the following information in the format of the locale:
//YYYY-MM-dd HH:mm:ss z (Z is time zone)
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];
return dateFormatter;
}
+ (NSDateFormatter *)dateFormatterWithoutYear {
NSDateFormatter *dateFormatter = [Constants getDateFormatterWithTimeZone];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *format = [dateFormatter dateFormat];
format = [format stringByReplacingOccurrencesOfString:#"/yy" withString:#""];
NSRange secondSpace;
secondSpace.location = format.length-2;
secondSpace.length = 1;
format = [format stringByReplacingCharactersInRange:secondSpace withString:#""];
[dateFormatter setDateFormat:format];
return dateFormatter;
}
+ (NSDateFormatter *) dateFormatterMonthDayOnly {
NSDateFormatter *dateFormatter = [Constants getDateFormatterWithTimeZone];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *format = [dateFormatter dateFormat];
format = [format stringByReplacingOccurrencesOfString:#"/yy" withString:#""];
NSRange range;
range.location = 0;
range.length = 3;
format = [format substringWithRange:range];
[dateFormatter setDateFormat:format];
return dateFormatter;
}
+ (NSDateFormatter *) getTitleDateFormatter {
//Returns the following information in the format of the locale:
//MM-dd-yyyy hh:mm:ssa
NSDateFormatter *dateFormatter = [Constants getDateFormatterWithTimeZone];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
NSString *format = [dateFormatter dateFormat];
NSRange secondSpace;
secondSpace.location = format.length-2;
secondSpace.length = 1;
format = [format stringByReplacingOccurrencesOfString:#"/" withString:#"-"];
format = [format stringByReplacingCharactersInRange:secondSpace withString:#""];
[dateFormatter setDateFormat:format];
return dateFormatter;
}
First off, make sure you set the behavior to 10.4 - more modern, works better in my experience.
[dateTimeFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
Next, you can't use the same format to parse and format if they have 2 different string representations, so use 2 formatters, or change the string format between parsing and then formatting.
Also make sure you consider the formatting options:
http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1
lowercase is e is the day of week, lowercase d is the day of the month.
For month, use MMMM, not B.
You want to use [NSFormatter dateFromString:] to convert your string-based date to an NSDate instance. From there you want to use stringFromDate with the NSDate, not the string as you have written above. I'm not sure about using the same NSDateFormatter for both parsing and formatting - you may need two separate instances to handle the different format styles.