Respuestas:
Qué tal si...
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)
}
init
con NSDateFormatter
. Fue eliminado después de iOS 3.2 . (Y si se utiliza un método de clase en su lugar, se AutoRelease y usted no tendrá el problema de pérdida, también.)
init
en varios lugares.
No sé cómo todos nos perdimos esto: localizedStringFromDate: dateStyle: timeStyle:
NSString *dateString = [NSDateFormatter localizedStringFromDate:[NSDate date]
dateStyle:NSDateFormatterShortStyle
timeStyle:NSDateFormatterFullStyle];
NSLog(@"%@",dateString);
salidas '13 / 06/12 00:22:39 GMT + 03: 00 '
Esperamos agregar más valor al proporcionar el formateador normal, incluido el año, mes y día con la hora. Puedes usar este formateador por más de un año
[dateFormat setDateFormat: @"yyyy-MM-dd HH:mm:ss zzz"];
hay una serie de NSDate
ayudantes en la web, tiendo a usar:
https://github.com/billymeltdown/nsdate-helper/
Extracto de léame a continuación:
NSString *displayString = [NSDate stringForDisplayFromDate:date];
Esto produce los siguientes tipos de salida:
‘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 ;-)
En 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);
Si no tienes NSDate
-descriptionWithCalendarFormat:timeZone:locale:
disponible (no creo que iPhone / Cocoa Touch incluya esto), es posible que necesites usar strftime y monkey con algunas cadenas de estilo C. Puede obtener la marca de tiempo UNIX de un NSDate
uso 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;
}
Solo agrega esta extensión:
extension NSDate {
var stringValue: String {
let formatter = NSDateFormatter()
formatter.dateFormat = "yourDateFormat"
return formatter.stringFromDate(self)
}
}
respuesta rápida 4
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)
}
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];
Es un formato rápido:
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