¿Cómo obtengo el día de la semana y / o el nombre del mes de una variable NSDate?
Muy bien. El problema que tenemos es que tenemos NSStrings llenos de fechas en el formato de aaaaMMdd y lo que queremos hacer es obtener el día de la semana actual y el nombre del mes. La función dagOmvandlare convierte el datestring en día de la semana y mes. La función se llama entonces en viewDidLoad para nombrar todos nuestros títulos de botones de inglés a sueco meses.
Nuestra solución actual se ve así:
-(NSString *)dagOmvandlare:(id) suprDatum{
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = @"yyyyMMdd";
NSDate *date = [dateFormatter dateFromString:suprDatum];
NSString * monthString = [date descriptionWithCalendarFormat:@"%B"timeZone:nil
locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]];
if ([monthString isEqualToString:@"January"]) {
monthString = @"Januari";
}
else
if ([monthString isEqualToString:@"February"]) {
monthString = @"Februari";
}
else
if ([monthString isEqualToString:@"May"]) {
monthString = @"Maj";
}
else
if ([monthString isEqualToString:@"June"]) {
monthString = @"Juni";
}
else
if ([monthString isEqualToString:@"July"]) {
monthString = @"Juli";
}
else
if ([monthString isEqualToString:@"August"]) {
monthString = @"Augusti";
}
else
if ([monthString isEqualToString:@"October"]) {
monthString = @"Oktober";
}
else
if ([monthString isEqualToString:@"March"]) {
monthString = @"Mars";
}
return monthString;
}
- (void)viewDidLoad {
[super viewDidLoad];
[button3 setTitle:(NSString *)[self dagOmvandlare:self.datum1] forState:UIControlStateNormal];
[button2 setTitle:(NSString *)[self dagOmvandlare:self.datum2] forState:UIControlStateNormal];
[bmanad1 setTitle:(NSString *)[self dagOmvandlare:self.datum3] forState:UIControlStateNormal];
}
Y lo que hemos descubierto hasta ahora es que la
NSString * monthString = [date descriptionWithCalendarFormat:@"%B"timeZone:nil
locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]];
No está permitido para ser utilizado por las pautas de Apples con respecto a las API no públicas. Así que la pregunta principal es, ¿qué otra manera hay para obtener el día de la semana y el nombre del mes de nuestras datestrings que contienen fechas con el formato aaaaMMdd ?
7 answers
No es necesario convertir manualmente a las palabras suecas. El iPhone lo hará por ti. Prueba esto:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyyMMdd";
NSDate *date = [dateFormatter dateFromString:@"20111010"];
// set swedish locale
dateFormatter.locale=[[NSLocale alloc] initWithLocaleIdentifier:@"sv_SE"];
dateFormatter.dateFormat=@"MMMM";
NSString *monthString = [[dateFormatter stringFromDate:date] capitalizedString];
NSLog(@"month: %@", monthString);
dateFormatter.dateFormat=@"EEEE";
NSString *dayString = [[dateFormatter stringFromDate:date] capitalizedString];
NSLog(@"day: %@", dayString);
Salida:
month: Oktober
day: Måndag
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-28 06:55:39
Extensiones simples de Swift 3:
// Weekday
extension Date {
func dayOfWeek() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
return dateFormatter.string(from: self).capitalized
// or capitalized(with: locale)
}
}
print(Date().dayOfWeek()!) // Wednesday
// Month Name
extension Date {
func monthName() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM"
return dateFormatter.string(from: self).capitalized
// or capitalized(with: locale)
}
}
print(Date().monthName()!) // October
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-23 16:55:38
NSString *strDate=@"20110407";
NSDateFormatter *df=[[[NSDateFormatter alloc] init] autorelease];
[df setDateFormat:@"yyyyMMdd"];
NSDate *targetDate=[df dateFromString:strDate];
[df setDateFormat:@"EEEE MMMM dd, yyyy"];
NSString *s=[df stringFromDate:targetDate];
NSLog(@"Date: %@", s);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-08 07:20:29
Espero que esto ayude
NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate *date = [NSDate 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];
[calendar release];
Esto podría ser útil
Otra pregunta SO que podría ayudarle Cómo encontrar el día de la semana a partir de la fecha de hoy usando NSDate?
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:08
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE"];
NSString *dayName = [dateFormatter stringFromDate:Date];
Este nombre de día estará disponible en la configuración regional del usuario.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-27 18:44:06
Como dice Apple, crear (y dejar que ARC disponga) un formateador es caro, así que:
1) declare en su archivo:
private var localDateFormatter : DateFormatter?
..
extension Date {
2) utilice el enfoque perezoso:
if localDateFormatter == nil{
localDateFormatter = DateFormatter()
let locale = Locale(identifier: "en_US_POSIX")
....}
let newTime = localDateFormatter!.date(from: self)
Si tienes alla las cosas en una clase, un miembro static / let estaría bien. (no podemos usar vars en extensiones... : (globals parece malo, pero de ninguna manera...)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-20 12:13:50
- (void) getMonthFromDate:(NSString *) stringDate
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [dateFormat dateFromString:stringDate];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date]; // Get necessary date components
NSLog(@"%lu", [components day]);
NSLog(@"%lu %@",[components day],[[dateFormat monthSymbols] objectAtIndex:[components month]]);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-03 08:21:07