关于objective c:将NSDate转换为NSString

Convert NSDate to NSString

如何将NSDate转换为NSString,以便只将@"yyyy"格式的年份输出到字符串?


怎么样...

1
2
3
4
5
6
7
8
9
10
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:

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


我不知道我们都错过了这个:localizedStringFromDate:dateStyle:timeStyle:

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

输出'13 / 06/12 00:22:39 GMT + 03:00'


希望通过提供包括年,月,日在内的常规格式化程序来增加更多价值。
您可以使用此格式化程序超过一年

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

希望这有助于更多人

干杯


网上有很多NSDate助手,我倾向于使用:

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

自述文件摘要如下:

1
  NSString *displayString = [NSDate stringForDisplayFromDate:date];

这会产生以下类型的输出:

1
2
3
4
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 ;-)


在Swift中:

1
2
3
var formatter = NSDateFormatter()
formatter.dateFormat ="yyyy"
var dateString = formatter.stringFromDate(YourNSDateInstanceHERE)


1
2
3
4
  NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
  [dateformate setDateFormat:@"yyyy"]; // Date formater
  NSString *date = [dateformate stringFromDate:[NSDate date]]; // Convert date to string
  NSLog(@"date :%@",date);


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
+(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;
}

如果你没有NSDate -descriptionWithCalendarFormat:timeZone:locale:可用(我不相信iPhone / Cocoa Touch包含这个),你可能需要使用strftime并使用一些C风格的字符串。您可以使用NSDate -timeIntervalSince1970NSDate获取UNIX时间戳。


只需添加此扩展程序:

1
2
3
4
5
6
7
extension NSDate {
    var stringValue: String {
        let formatter = NSDateFormatter()
        formatter.dateFormat ="yourDateFormat"
        return formatter.stringFromDate(self)
    }
}

如果你使用的是Mac OS X,你可以写:

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

但是,这在iOS上不可用。


迅速4回答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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)

}


它的格式很快:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

定义您自己的实用程序,以格式化您的日期日期格式
例如。

1
2
3
4
5
6
NSString * stringFromDate(NSDate *date)  
 {   NSDateFormatter *formatter
    [[NSDateFormatter alloc] init];  
    [formatter setDateFormat:@"MM ∕ dd ∕ yyyy, hh?mm a"];    
    return [formatter stringFromDate:date];
}

1
2
3
4
5
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];