Pergunta

Como faço para converter, NSDate para NSString para que apenas o ano em @ "aaaa" formato é saída para a cadeia?

Foi útil?

Solução

Que tal ...

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];

//Optionally for time zone conversions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];

NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];

//unless ARC is active
[formatter release];

Swift 4.2:

func stringFromDate(_ date: Date) -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "dd MMM yyyy HH:mm" //yyyy
    return formatter.string(from: date)
}

Outras dicas

Eu não sei como tudo o que perdeu esta: localizedStringFromDate: DateStyle: timeStyle:

NSString *dateString = [NSDateFormatter localizedStringFromDate:[NSDate date] 
                                                      dateStyle:NSDateFormatterShortStyle 
                                                      timeStyle:NSDateFormatterFullStyle];
NSLog(@"%@",dateString);

saídas '13 / 12/06 00:22:39 GMT + 03: 00'

Hope para agregar mais valor, fornecendo o formatador normal, incluindo o ano, mês e dia com o tempo. Você pode usar este formatador para mais do que apenas um ano

[dateFormat setDateFormat: @"yyyy-MM-dd HH:mm:ss zzz"]; 

Espero que isso ajude mais pessoas

Felicidades Al

há um número de ajudantes NSDate na web, que tendem a usar:

https://github.com/billymeltdown/nsdate-helper/

extrato Readme abaixo:

  NSString *displayString = [NSDate stringForDisplayFromDate:date];

Isso produz os seguintes tipos de saída:

‘3:42 AM’ – if the date is after midnight today
‘Tuesday’ – if the date is within the last seven days
‘Mar 1’ – if the date is within the current calendar year
‘Mar 1, 2008’ – else ;-)

Em Swift:

var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy"
var dateString = formatter.stringFromDate(YourNSDateInstanceHERE)
  NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
  [dateformate setDateFormat:@"yyyy"]; // Date formater
  NSString *date = [dateformate stringFromDate:[NSDate date]]; // Convert date to string
  NSLog(@"date :%@",date);

Se você não tem NSDate -descriptionWithCalendarFormat:timeZone:locale: disponível (eu não acredito iPhone / Cocoa Touch inclui este) pode ser necessário o uso strftime e macaco ao redor com algumas cordas de estilo C. Você pode obter o timestamp UNIX a partir de um NSDate usando NSDate -timeIntervalSince1970.

+(NSString*)date2str:(NSDate*)myNSDateInstance onlyDate:(BOOL)onlyDate{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if (onlyDate) {
        [formatter setDateFormat:@"yyyy-MM-dd"];
    }else{
        [formatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
    }

    //Optionally for time zone conversions
    //   [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];

    NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];
    return stringFromDate;
}

+(NSDate*)str2date:(NSString*)dateStr{
    if ([dateStr isKindOfClass:[NSDate class]]) {
        return (NSDate*)dateStr;
    }

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [dateFormat dateFromString:dateStr];
    return date;
}

Basta adicionar esta extensão:

extension NSDate {
    var stringValue: String {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yourDateFormat"
        return formatter.stringFromDate(self)
    }
}

Se você estiver em Mac OS X, você pode escrever:

NSString* s = [[NSDate date] descriptionWithCalendarFormat:@"%Y_%m_%d_%H_%M_%S" timeZone:nil locale:nil];

No entanto, este não está disponível no iOS.

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:myNSDateInstance];
NSInteger year = [components year];
// NSInteger month = [components month];
NSString *yearStr = [NSString stringWithFormat:@"%ld", year];

Defina seu próprio utilitário para o formato de sua data exigida formato de data para, por exemplo.

NSString * stringFromDate(NSDate *date)  
 {   NSDateFormatter *formatter
    [[NSDateFormatter alloc] init];  
    [formatter setDateFormat:@"MM ∕ dd ∕ yyyy, hh꞉mm a"];    
    return [formatter stringFromDate:date]; 
}

É de formato rápida:

func dateFormatterWithCalendar(calndarIdentifier: Calendar.Identifier, dateFormat: String) -> DateFormatter {

    let formatter = DateFormatter()
    formatter.calendar = Calendar(identifier: calndarIdentifier)
    formatter.dateFormat = dateFormat

    return formatter
}


//Usage
let date = Date()
let fotmatter = dateFormatterWithCalendar(calndarIdentifier: .gregorian, dateFormat: "yyyy")
let dateString = fotmatter.string(from: date)
print(dateString) //2018

rápida 4 resposta

static let dateformat: String = "yyyy-MM-dd'T'HH:mm:ss"
public static func stringTodate(strDate : String) -> Date
{

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateformat
    let date = dateFormatter.date(from: strDate)
    return date!
}
public static func dateToString(inputdate : Date) -> String
{

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateformat
    return formatter.string(from: inputdate)

}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top