Pregunta

Básicamente necesito obtener la fecha y hora actuales por separado, formateadas como:

2009-04-26 
11:06:54

El siguiente código, de otra pregunta sobre el mismo tema, genera

now:        |2009-06-01 23:18:23 +0100| 
dateString: |Jun 01, 2009 23:18| 
parsed:     |2009-06-01 23:18:00 +0100|

Esto es casi lo que estoy buscando, pero quiero separar el día y la hora.

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"MMM dd, yyyy HH:mm"];

NSDate *now = [[NSDate alloc] init];

NSString *dateString = [format stringFromDate:now];

NSDateFormatter *inFormat = [[NSDateFormatter alloc] init];
[inFormat setDateFormat:@"MMM dd, yyyy"];

NSDate *parsed = [inFormat dateFromString:dateString];

NSLog(@"\n"
"now:        |%@| \n"
"dateString: |%@| \n"
"parsed:     |%@|", now, dateString, parsed);
¿Fue útil?

Solución

iPhone cadenas de formato están en formato Unicode . Detrás del enlace es una tabla que explica lo que todas las cartas encima del nivel medio para que pueda construir su propio.

Y, por supuesto, no se olvide de liberar sus formateadores fecha cuando haya terminado con ellos. El código anterior se filtra format, now, y inFormat.

Otros consejos

Esto es lo que solía:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];

NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"HH:mm:ss"];

NSDate *now = [[NSDate alloc] init];

NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];

NSLog(@"\n"
      "theDate: |%@| \n"
      "theTime: |%@| \n"
      , theDate, theTime);

[dateFormat release];
[timeFormat release];
[now release];

Puede utilizar este método sólo tiene que pasar su fecha a ella

-(NSString *)getDateFromString:(NSString *)string
{

    NSString * dateString = [NSString stringWithFormat: @"%@",string];

    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"your current date format"];
    NSDate* myDate = [dateFormatter dateFromString:dateString];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"your desired format"];
    NSString *stringFromDate = [formatter stringFromDate:myDate];

    NSLog(@"%@", stringFromDate);
    return stringFromDate;
}
    NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
    [dateformat setDateFormat:@"Your Date Format"];

establecer el formato de volver es ....

yyyy-MM-dd fecha de regreso 2015-12-17

yyyy-MMM-dd fecha de regreso 2015-Dec-17

yy-MM-dd fecha de regreso 15-12-17

dd-MM-yy fecha de regreso 17-12-15

dd-MM-yyyy fecha de regreso 17-12-2015

fecha y hora de regreso yyyy-MMM-dd HH:mm:ss 2015-Dec-17 08:07:13

fecha y hora de regreso yyyy-MMM-dd HH:mm 2015-Dec-17 08:07

Para obtener más detalles de Datos y Formato de hora para click Ahora.

Gracias .....

nada nuevo, pero todavía quiere compartir mi método:

+(NSString*) getDateStringFromSrcFormat:(NSString *) srcFormat destFormat:(NSString *)
destFormat scrString:(NSString *) srcString
{
    NSString *dateString = srcString;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //[dateFormatter setDateFormat:@"MM-dd-yyyy"];
    [dateFormatter setDateFormat:srcFormat];
    NSDate *date = [dateFormatter dateFromString:dateString];

    // Convert date object into desired format
    //[dateFormatter setDateFormat:@"yyyy-MM-dd"];
    [dateFormatter setDateFormat:destFormat];
    NSString *newDateString = [dateFormatter stringFromDate:date];
    return newDateString;
}

Para rápida

var dateString:String = "2014-05-20";
var dateFmt = NSDateFormatter()
// the format you want
dateFmt.dateFormat = "yyyy-MM-dd"
var date1:NSDate = dateFmt.dateFromString(dateString)!;

veloz 3

extension Date {

    func toString(template: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: template, options: 0, locale: NSLocale.current)
        return formatter.string(from: self)
    }

}

Uso

let now = Date()
let nowStr0 = now.toString(template: "EEEEdMMM") // Tuesday, May 9
let nowStr1 = now.toString(template: "yyyy-MM-dd") // 2017-05-09
let nowStr2 = now.toString(template: "HH:mm:ss") // 17:47:09

Juegue con la plantilla que se adapte a sus necesidades.Ejemplos y documentación aquí para ayudarle a crear la plantilla que necesita.

Nota

Es posible que desee almacenar en caché su DateFormatter si planeas usarlo en TableView por ejemplo.Para dar una idea, recorrer más de 1000 fechas me llevó 0,5 segundos usando lo anterior toString(template: String) función, en comparación con 0,05 segundos usando myFormatter.string(from: Date).

NSDate *date         = [NSDate date];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"]
NSString *dateString  = [df stringFromDate:date];
[df setDateFormat:@"hh:mm:ss"];
NSString *hoursString = [df stringFromDate:date];

Eso es todo, lo tienes todo lo que quiera.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top