I know that the NSDateformatter suite of functionality is a boon for mankind, but at the same time it is very confusing to me. I hope you can help me out.
Somewhere in my code, there is an int representing a month. So: 1 would be January, 2 February, etc.
In my user interface, I would like to display this integer as proper month name. Moreover, it should adhere to the locale of the device.
Thank you for your insights
In the mean time, I have done the following:
int monthNumber = 11
NSString * dateString = [NSString stringWithFormat: #"%d", monthNumber];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
[dateFormatter release];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMMM"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
[formatter release];
is this the way to do it? It seems a bit wordy.
Another option is to use the monthSymbols method:
int monthNumber = 11; //November
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
NSString *monthName = [[df monthSymbols] objectAtIndex:(monthNumber-1)];
Note that you'll need to subtract 1 from your 1..12 monthNumber since monthSymbols is zero-based.
let monthName = DateFormatter().monthSymbols[monthNumber - 1]
You can change the dateFormat of the NSDateFormatter. So to simplify your code:
int monthNumber = 11
NSString * dateString = [NSString stringWithFormat: #"%d", monthNumber];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
[formatter setDateFormat:#"MMMM"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
[dateFormatter release];
You should also set the locale once you init the date formatter.
dateFormatter.locale = [NSLocale currentLocale]; // Or any other locale
Hope this helps
Best solution for this is , standaloneMonthSymbols method,
-(NSString*)MonthNameString:(int)monthNumber
{
NSDateFormatter *formate = [NSDateFormatter new];
NSArray *monthNames = [formate standaloneMonthSymbols];
NSString *monthName = [monthNames objectAtIndex:(monthNumber - 1)];
return monthName;
}
How about:
NSUInteger i = <your month integer>;
NSDateFormatter *df = [NSDateFormatter new];
// change locale if the standard is not what you want
NSArray *monthNames = [df standaloneMonthSymbols];
NSString *monthName = [monthNames objectAtIndex:(i - 1)];
[df release];
Both answers from Anna Karenina and Carl doesn't work that well as they won't return month name in nominativ for some cultures. I suggest to use the proposed solution from Pascal, which solves this issue (by replacing monthSymbols with standaloneMonthSymbols)
In Swift 3.0
let monthNumber = 3
let fmt = DateFormatter()
fmt.dateFormat = "MM"
let month = fmt.monthSymbols[monthNumber - 1]
print(month)
// result
"March\n"
Swift 4.X
print((DateFormatter().monthSymbols[month-1].capitalized)) //month is int less than 12
For Example:
print((DateFormatter().monthSymbols[11-1].capitalized))
Output
November
NSDate to NSString -> As Dateformat Ex: 2015/06/24
NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
[dateformate setDateFormat: #"yyyy/MM/dd"];
NSString *date = [dateformate stringFromDate:selectedDate]; // Convert date to string
NSDate to NSString -> As Dateformat Ex: 2015 June 24, 1:02 PM
[dateformate setDateFormat:#"yyyy MMMM dd, h:mm a"];
NSString *displayDate = [dateformate stringFromDate:selectedDate]; // Convert date to string
NSLog(#"date :%#",date);
NSLog(#"Display time = %#", displayDate);
And with ARC :
+ (NSString *)monthNameFromDate:(NSDate *)date {
if (!date) return #"n/a";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MM"];
return [[df monthSymbols] objectAtIndex:([[df stringFromDate:date] integerValue] - 1)];
}
You should be able to get rid of the release and re-allocation of the dateFormatter, cutting out a couple of lines, but that's all I see.
Related
This question already has answers here:
Converting string MM/DD/YYYY to NSDate
(4 answers)
Closed 6 years ago.
I can't figure out what i'm doing wrong.
Trying get NSString with current date with format yyyy-mm-dd.
_convenienceFormatter = [[NSDateFormatter alloc] init];
_convenienceFormatter.dateFormat = #"yyyy-mm-dd";
NSString *string = [_convenienceFormatter stringFromDate:[NSDate date]];
Output is : 2016-37-14
What am i doing wrong?
I tried your coding
NSDateFormatter *convenienceFormatter = [[NSDateFormatter alloc] init];
convenienceFormatter.dateFormat = #"yyyy-mm-dd";
NSString *string = [convenienceFormatter stringFromDate:[NSDate date]];
It gives me 2016-14-14
NSDateFormatter *Formatter = [[NSDateFormatter alloc] init];
Formatter.dateFormat = #"yyyy-MM-dd";
NSString *stringFor = [Formatter stringFromDate:[NSDate date]];
But above code gives me 2016-07-14
NOTE: Generally mm indicates minutes.MM indicates month
Date Formatting Table
Dates
Date Programming
Date Formatter
You need to change your date formatter to MM instead of mm because mm is for minute change your code like this
_convenienceFormatter = [[NSDateFormatter alloc] init];
_convenienceFormatter.dateFormat = #"yyyy-MM-dd";
NSString *string = [_convenienceFormatter stringFromDate:[NSDate date]];
You need to write MM and not mm.
_convenienceFormatter = [[NSDateFormatter alloc] init];
_convenienceFormatter.dateFormat = #"yyyy-MM-dd";
NSString *string = [_convenienceFormatter stringFromDate:[NSDate date]];
Try this helper method.
-(NSString *) getCurrentDate {
NSDateFormatter *dateformater = [[NSDateFormatter alloc]init];
[dateformater setDateFormat:#"yyyy-MM-dd"];
NSString *today=[dateformater stringFromDate:[NSDate date]];
return today;
}
I try to set a specific format to my NSString date, but I am a little confused about how to retrieve some part of my string.
My string date is : #"2008-06-26T00:00:00+0100" and I would like to transform it in "06/2008".
This is my method :
- (NSString *)formatDate: (NSString *) myDate {
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"MM/yyyy"];
NSDate * aDate = [df dateFromString:myDate];
NSString *stringFromDate = [df stringFromDate:aDate];
return stringFromDate;
}
I know that the format I try to set doesn't respect the format I put in setDateFormat but I don't know what to define, because I want to retrieve only the month and the year.
Try this :
(NSString *)formatDate: (NSString *) myDate {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *date = [dateFormatter dateFromString:myDate];
NSDateFormatter *dF = [[NSDateFormatter alloc] init];
[dF setDateFormat:#"MM/yyyy"];
NSString *stringFromDate = [dF stringFromDate:dte];
return stringFromDate
}
OK, I know I am missing something but I don't know what.
My NSDateFormmater comes up in the textField(personMonthdayTextField) with todays date but when I selected the datePicker and input it into the textField, it comes up with the standard format with the hours, minutes, seconds which I don't need.
Any help is appreciated.
Thanks
-(void)viewDidLoad {
NSDate* date = [NSDate date];
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MMM/yyyy"];
NSString* str = [formatter stringFromDate:date];
NSLog(#"%#",str);
NSMutableArray *Arr=[str componentsSeparatedByString:#" "];
personMonthdayTextField.text=[Arr objectAtIndex:0];
}
- (IBAction)done:(id)sender {
NSDate *dateSelected = [datepick date];
NSString *dateStamp = [[NSString alloc]initWithFormat:#"%#", dateSelected];
personMonthdayTextField.text = dateStamp;
}
This will give you date only
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
datelabel.text = [NSString stringWithFormat:#"%#",
[df stringFromDate:[NSDate date]]];
Adapt this for your code under your IBAction method
just use NSDateFormatter in your IBAction
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
NSDate *dateSelected = [datepick date];
personMonthdayTextField.text = [dateFormatter stringFromDate:dateSelected];
you can also tweak with formats of date give in Apple ios sdk ,easily to get desired format.
If you only want the day why don't you set the dateFormat as "dd", it would save the need to separate the components of dateString.
-(void)viewDidLoad {
NSDate* date = [NSDate date];
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd"];
personMonthdayTextField.text = [formatter stringFromDate:date];
}
- (IBAction)done:(id)sender {
NSDate *dateSelected = [datepick date];
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd"];
personMonthdayTextField.text = [formatter stringFromDate:date];
}
Hi in my project I have Textfield as from and another is delay for ex in From filed I have value as "18:30"(string) and in delay filed "18" (integer) ,now I need to add these two value and should display value like "18:48"(string) in another textfield.If anyone know guide me thanks
Please refer to the following code for your query.
NSString *str=#"18:30";
int addTime=18;
NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm"];
NSDate *dateInput=[formatter dateFromString:str];
dateInput=[dateInput dateByAddingTimeInterval:addTime*60];
NSString *dateOutPut=[formatter stringFromDate:dateInput];
NSLog(#"OutputDate= %#",dateOutPut);
Console Output:
18:48
NSString *str=#"18:30";
int addTime=18;
NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm"];
NSDate *dateInput=[formatter dateFromString:str];
dateInput=[dateInput dateByAddingTimeInterval:addTime*60];
NSString *dateOutPut=[formatter stringFromDate:dateInput];
NSLog(#"OutputDate= %#",dateOutPut);
//convert string object into NSDate object
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm a"];
//Set System Timezone
[formatter setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *TimeInDateFormat = [formatter dateFromString:#"12:45 AM"];
//Additing 01:00 Houes
NSTimeInterval secondsInOneHours = 1 * 60 * 60;
NSDate *dateOneHoursAhead = [TimeInDateFormat
dateByAddingTimeInterval:secondsInOneHours];
NSLog(#"after added dateOneHoursAhead: %#",dateOneHoursAhead);
abow code output is :
after added dateOneHoursAhead: 01:45 PM
try now........
Here is swift version.
let str: String = "10:30"
let addTime: Int = 30 //minutes
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
var dateInput: Date? = formatter.date(from: str)
dateInput = dateInput?.addingTimeInterval(TimeInterval(addTime*60))
endtime = formatter.string(from: dateInput!)
Thanks to #Andy Paul for objective c version of code.
I am trying to set the date format for something like "2011-04-21 03:31:37.310396". I think I'm not getting the fractional seconds right. I'm looking at http://unicode.org/reports/tr35/tr35-10.html#Date_Format_Patterns for guidelines on how to specify it and I think my issue is in the format itself.
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = #"yyyy-MM-dd HH:mm:ssSSSSSS";
NSDate* serverDate = [dateFormatter dateFromString:stringFormOfDate];
Help?
try
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = #"yyyy-MM-dd HH:mm:ss.SSSSSS";
NSDate* serverDate = [dateFormatter dateFromString:#"2011-04-21 03:31:37.310396"];
NSLog(#"%#", serverDate);
I guess you probably forgot the dot
As per Zaph's comment in the other answer: the maximum number of S is 3. Any more just produce zeros.
E.g.
dateFormatter.dateFormat = #"yyyy-MM-dd HH:mm:ss.SSSSSS"; // Last 3 'S' ignored.
Then #"2011-04-21 03:31:37.311396" will produce 2011-04-21 03:31:37.311000
To maintain full microsecond precision try this magic:
-(NSDate *)_dateFromUtcString:(NSString *)utcString{
if(!utcString){
return nil;
}
static NSDateFormatter *df = nil;
if (df == nil) {
df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[df setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
}
NSArray* parts = [utcString componentsSeparatedByString:#"."];
NSDate *utcDate = [df dateFromString:parts[0]];
if(parts.count > 1){
double microseconds = [parts[1] doubleValue];
utcDate = [utcDate dateByAddingTimeInterval:microseconds / 1000000];
}
return utcDate;
}
Now an NSString "2011-04-21 03:31:37.310396" will parse fully to an NSDate 2011-04-21 03:31:37.310396