将NSDate转换为NSString

我如何转换,NSDateNSString,以便只有年份在@“yyyy”格式输出到字符串?

326304 次浏览

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

如何……

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)
}
希望通过提供包括年、月、日和时间在内的正常格式化程序来增加更多的价值。 您可以使用此格式化程序超过一年

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

在网络上有很多NSDate帮助,我倾向于使用:

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

自述摘录如下:

  NSString *displayString = [NSDate stringForDisplayFromDate:date];

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

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

如果你在Mac OS X上,你可以这样写:

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

但是这在iOS上是不可用的。

我不知道为什么我们都错过了这个:< a href = " https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html / / apple_ref / occ / clm / NSDateFormatter / localizedStringFromDate % 3 adatestyle % 3 atimestyle % 3“> localizedStringFromDate: dateStyle: timeStyle: < / >

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

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

  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;
}

迅速:

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

只需添加这个扩展:

extension NSDate {
var stringValue: String {
let formatter = NSDateFormatter()
formatter.dateFormat = "yourDateFormat"
return formatter.stringFromDate(self)
}
}
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];
定义你自己的实用程序格式你的日期所需的日期格式 例如。< / p >
NSString * stringFromDate(NSDate *date)
{   NSDateFormatter *formatter
[[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM ∕ dd ∕ yyyy, hh꞉mm a"];
return [formatter stringFromDate:date];
}

swift格式:

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

迅速回答

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)


}

#ios #swift #convertDateinString

简单地像这样做“convert date into string”;根据您传递的格式:

let formatter = DateFormatter()


formatter.dateFormat = "dd-MM-YYYY" // pass formate here
        

let myString = formatter.string(from: date) // this will convert Date in String

注意:你可以指定不同的格式,如"yyyy-MM-dd""yyyy""MM"等…

iOS 15更新

iOS 15现在支持直接在Date对象上调用.formatted,而不需要显式的DateFormatter

常见格式示例

文档

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)

替代语法

文档

// 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())

使用extension来获得清晰的代码


您可以编写一个扩展来将任何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)
}
}

然后这样使用它:

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
要学习如何指定你的需要的格式字符串,请看这个链接
有关如何格式化日期的完整参考,请参阅苹果的官方日期格式指南 在这里.

objective - c:

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

迅速:

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

这是nsdateformatter的一个好网站。你可以在不同的本地预览不同DateFormatter的日期字符串。

enter image description here

简单的方法,使用c#风格的方式将日期转换为字符串。

用法:

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




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

扩展:

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
}
}