简体   繁体   English

将 NSDate 转换为 NSString

[英]Convert NSDate to NSString

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

How about...怎么样...

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 :斯威夫特 4.2:

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

I don't know how we all missed this: localizedStringFromDate:dateStyle:timeStyle:我不知道我们怎么都错过了这个: localizedStringFromDate:dateStyle:timeStyle:

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

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

Hope to add more value by providing the normal formatter including the year, month and day with the time.希望通过提供包括年、月和日在内的普通格式化程序来增加更多的价值。 You can use this formatter for more than just a year您可以使用此格式化程序超过一年

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

there are a number of NSDate helpers on the web, I tend to use:网络上有许多NSDate助手,我倾向于使用:

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

Readme extract below:自述文件摘录如下:

  NSString *displayString = [NSDate stringForDisplayFromDate:date];

This produces the following kinds of output:这会产生以下类型的输出:

‘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 ;-)

In 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);
+(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;
}

Just add this extension:只需添加此扩展名:

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

If you don't have NSDate -descriptionWithCalendarFormat:timeZone:locale: available (I don't believe iPhone/Cocoa Touch includes this) you may need to use strftime and monkey around with some C-style strings.如果你没有NSDate -descriptionWithCalendarFormat:timeZone:locale:可用(我不相信 iPhone/Cocoa Touch 包括这个)你可能需要使用 strftime 和一些 C 风格的字符串。 You can get the UNIX timestamp from an NSDate using NSDate -timeIntervalSince1970 .您可以使用NSDate -timeIntervalSince1970NSDate获取 UNIX 时间戳。

If you are on Mac OS X you can write:如果您使用的是 Mac OS X,您可以编写:

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

However this is not available on iOS.但是,这在 iOS 上不可用。

swift 4 answer迅速 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];

Define your own utility for format your date required date format for eg.定义您自己的实用程序来格式化您的日期所需的日期格式,例如。

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

It's swift format :这是快速格式:

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

#ios #swift #convertDateinString #ios #swift #convertDateinString

Simply just do like this to "convert date into string" as per format you passed:只需按照您传递的格式执行此操作即可“将日期转换为字符串”:

let formatter = DateFormatter()

formatter.dateFormat = "dd-MM-YYYY" // pass formate here
        
let myString = formatter.string(from: date) // this will convert Date in String

Note: You can specify different formats such like "yyyy-MM-dd" , "yyyy" , "MM" etc...注意:您可以指定不同的格式,例如"yyyy-MM-dd""yyyy""MM"等...

Update for iOS 15 iOS 15 更新

iOS 15 now supports calling .formatted on Date objects directly without an explicit DateFormatter . iOS 15 现在支持在没有显式DateFormatter情况下直接在Date对象上调用.formatted

Example for common formats常见格式示例

Documentation 文档

date.formatted() // 6/8/2021, 7:30 PM
date.formatted(date: .omitted, time: .complete) // 19:30
date.formatted(date: .omitted, time: .standard) // 07:30 PM
date.formatted(date: .omitted, time: .shortened) // 7:30 PM
date.formatted(date: .omitted, time: .omitted)

Alternative syntax替代语法

Documentation 文档

// We can also specify each DateComponent separately by chaining modifiers.
date.formatted(.dateTime.weekday(.wide).day().month().hour().minute())
// Tuesday, Jun 8, 7:30 pm

// Answer to specific question
date.formatted(.dateTime.year())

Use extension to have clear code使用extension有清晰的代码


You can write an extension to convert any Date object to any desired calendar and any format您可以编写一个扩展来将任何Date对象转换为任何所需的日历和任何格式

extension Date{
    func asString(format: String = "yy/MM/dd HH:mm",
                  for identifier: Calendar.Identifier = .persian) -> String {
        let formatter = DateFormatter()
        formatter.calendar = Calendar(identifier: identifier)
        formatter.dateFormat = format
        
        return formatter.string(from: self)
    }
}

Then use it like this:然后像这样使用它:

let now = Date()

print(now.asString())  // prints -> 00/04/18 20:25
print(now.asString(format: "yyyy/MM/dd"))  // prints -> 1400/04/18
print(now.asString(format: "MM/dd", for: .gregorian))  //  prints -> 07/09  

To learn how to specify your desired format string take a look at this link .要了解如何指定所需的格式字符串,请查看此链接
For a complete reference on how to format dates see Apple 's official Date Formatting Guide here .有关如何格式化日期的完整参考,请参阅此处的Apple官方日期格式化指南

for Objective-C:对于 Objective-C:

NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = @"yyyy";
NSString *dateString = [formatter stringFromDate:date];

for Swift:对于斯威夫特:

let now = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy"
let dateString = formatter.string(from: now) 

That's a good website for nsdateformatter .You can preview date strings with different DateFormatter in different local.这是一个很好的nsdateformatter网站。您可以在不同的本地使用不同的DateFormatter预览日期字符串。

在此处输入图片说明

Simple way to use C# styled way to convert Date to String.使用 C# 样式方式将日期转换为字符串的简单方法。

usage:用法:

let a = time.asString()
// 1990-03-25


let b = time.asString("MM ∕ dd ∕ yyyy, hh꞉mm a")
// 03 / 25 / 1990, 10:33 PM

extensions:扩展:

extension Date {
    func asString(_ template: String? = nil) -> String {
        if let template = template {
            let df = DateFormatter.with(template: template)
            
            return df.string(from: self)
        }
        else {
            return globalDateFormatter.string(from: self)
        }
    }
}

// Here you can set default template for DateFormatter
public let globalDateFormatter: DateFormatter = DateFormatter.with(template: "y-M-d")

public extension DateFormatter {
    static func with(template: String ) -> DateFormatter {
        let df = DateFormatter()
        df.dateFormat = template
        return df
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM