Jawaban:
Diperbarui: 2018
String to Date
var dateString = "02-03-2017"
var dateFormatter = DateFormatter()
// This is important - we set our input date format to match our input string
// if the format doesn't match you'll get nil from your string, so be careful
dateFormatter.dateFormat = "dd-MM-yyyy"
//`date(from:)` returns an optional so make sure you unwrap when using.
var dateFromString: Date? = dateFormatter.date(from: dateString)
Date to String
var formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
guard let unwrappedDate = dateFromString else { return }
//Using the dateFromString variable from before.
let stringDate: String = formatter.string(from: dateFromString)
Diperbarui: 20 Juli 2017
String ke NSDate
var dateString = "02-03-2017"
var dateFormatter = DateFormatter()
// This is important - we set our input date format to match our input string
// if the format doesn't match you'll get nil from your string, so be careful
dateFormatter.dateFormat = "dd-MM-yyyy"
var dateFromString = dateFormatter.date(from: dateString)
NSDate to String
var formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let stringDate: String = formatter.string(from: dateFromString)
Diperbarui: 22 Oktober 2015
String ke NSDate
var dateString = "01-02-2010"
var dateFormatter = NSDateFormatter()
// this is imporant - we set our input date format to match our input string
dateFormatter.dateFormat = "dd-MM-yyyy"
// voila!
var dateFromString = dateFormatter.dateFromString(dateString)
NSDate to String
var formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let stringDate: String = formatter.stringFromDate(NSDate())
println(stringDate)
NSString ke NSDate
NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [dateFormatter dateFromString:dateString];
NSDate dikonversi ke NSString:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", stringDate);
NSDate *dateFromString = [[NSDate alloc] init];
jika menetapkan nilai baru ke pointer di baris berikutnya ???
UPDATE 2019 (Swift 4):
Membuat Date
ekstensi untuk itu. Ini menggunakan NSDataDetector
alih-alih NSDateFormatter
.
// Just throw at it without any format.
var date: Date? = Date.FromString("02-14-2019 17:05:05")
Cukup menyenangkan, bahkan mengenali hal-hal seperti "Tomorrow at 5" .
XCTAssertEqual(Date.FromString("2019-02-14"), Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019.02.14"), Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019/02/14"), Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019 Feb 14"), Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019 Feb 14th"), Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("20190214"), Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("02-14-2019"), Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("02.14.2019 5:00 PM"), Date.FromCalendar(2019, 2, 14, 17))
XCTAssertEqual(Date.FromString("02/14/2019 17:00"), Date.FromCalendar(2019, 2, 14, 17))
XCTAssertEqual(Date.FromString("14 February 2019 at 5 hour"), Date.FromCalendar(2019, 2, 14, 17))
XCTAssertEqual(Date.FromString("02-14-2019 17:05:05"), Date.FromCalendar(2019, 2, 14, 17, 05, 05))
XCTAssertEqual(Date.FromString("17:05, 14 February 2019 (UTC)"), Date.FromCalendar(2019, 2, 14, 17, 05))
XCTAssertEqual(Date.FromString("02-14-2019 17:05:05 GMT"), Date.FromCalendar(2019, 2, 14, 17, 05, 05))
XCTAssertEqual(Date.FromString("02-13-2019 Tomorrow"), Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019 Feb 14th Tomorrow at 5"), Date.FromCalendar(2019, 2, 14, 17))
Seperti:
extension Date
{
public static func FromString(_ dateString: String) -> Date?
{
// Date detector.
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.date.rawValue)
// Enumerate matches.
var matchedDate: Date?
var matchedTimeZone: TimeZone?
detector.enumerateMatches(
in: dateString,
options: [],
range: NSRange(location: 0, length: dateString.utf16.count),
using:
{
(eachResult, _, _) in
// Lookup matches.
matchedDate = eachResult?.date
matchedTimeZone = eachResult?.timeZone
// Convert to GMT (!) if no timezone detected.
if matchedTimeZone == nil, let detectedDate = matchedDate
{ matchedDate = Calendar.current.date(byAdding: .second, value: TimeZone.current.secondsFromGMT(), to: detectedDate)! }
})
// Result.
return matchedDate
}
}
UPDATE 2014:
Membuat ekstensi NSString untuk itu.
// Simple as this.
date = dateString.dateValue;
Berkat NSDataDetector , ia mengenali banyak format.
'2014-01-16' dateValue is <2014-01-16 11:00:00 +0000>
'2014.01.16' dateValue is <2014-01-16 11:00:00 +0000>
'2014/01/16' dateValue is <2014-01-16 11:00:00 +0000>
'2014 Jan 16' dateValue is <2014-01-16 11:00:00 +0000>
'2014 Jan 16th' dateValue is <2014-01-16 11:00:00 +0000>
'20140116' dateValue is <2014-01-16 11:00:00 +0000>
'01-16-2014' dateValue is <2014-01-16 11:00:00 +0000>
'01.16.2014' dateValue is <2014-01-16 11:00:00 +0000>
'01/16/2014' dateValue is <2014-01-16 11:00:00 +0000>
'16 January 2014' dateValue is <2014-01-16 11:00:00 +0000>
'01-16-2014 17:05:05' dateValue is <2014-01-16 16:05:05 +0000>
'01-16-2014 T 17:05:05 UTC' dateValue is <2014-01-16 17:05:05 +0000>
'17:05, 1 January 2014 (UTC)' dateValue is <2014-01-01 16:05:00 +0000>
Bagian dari kit eppz ! , ambil kategori NSString + EPPZKit.h dari GitHub.
JAWABAN ASLI 2013:
Apakah Anda tidak yakin (atau tidak peduli) tentang format tanggal yang terkandung dalam string, gunakan NSDataDetector untuk tanggal parsing .
//Role players.
NSString *dateString = @"Wed, 03 Jul 2013 02:16:02 -0700";
__block NSDate *detectedDate;
//Detect.
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingAllTypes error:nil];
[detector enumerateMatchesInString:dateString
options:kNilOptions
range:NSMakeRange(0, [dateString length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
{ detectedDate = result.date; }];
NSString
-> 2013-09-11 01:31:22 +0000
mengkonversi ke NSDate
->2013-09-11 13:31:22 +0000
XCTAssertEqual(Date.FromString("2013-09-11 01:31:22 +0000"), Date.FromCalendar(2013, 9, 11, 1, 31, 22))
tampaknya baik-baik saja.
Saat menggunakan tanggal dengan format tetap, Anda perlu mengatur lokal formatter tanggal "en_US_POSIX"
.
Diambil dari Panduan Pemformatan Data
Jika Anda bekerja dengan tanggal format tetap, Anda harus terlebih dahulu mengatur lokal formatter tanggal ke sesuatu yang sesuai untuk format tetap Anda. Dalam kebanyakan kasus, lokal terbaik untuk dipilih adalah en_US_POSIX, lokal yang dirancang khusus untuk menghasilkan hasil bahasa Inggris AS terlepas dari preferensi pengguna dan sistem . en_US_POSIX juga invarian dalam waktu (jika AS, di beberapa titik di masa depan, mengubah cara format tanggal, en_US akan berubah untuk mencerminkan perilaku baru, tetapi en_US_POSIX tidak akan), dan di antara platform (en_US_POSIX berfungsi sama di iPhone OS seperti halnya pada OS X, dan seperti halnya pada platform lain).
Cepat 3 atau lebih baru
extension Formatter {
static let customDate: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "dd/MM/yy"
return formatter
}()
static let time: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "HH:mm"
return formatter
}()
static let weekdayName: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "cccc"
return formatter
}()
static let month: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "LLLL"
return formatter
}()
}
extension Date {
var customDate: String {
return Formatter.customDate.string(from: self)
}
var customTime: String {
return Formatter.time.string(from: self)
}
var weekdayName: String {
return Formatter.weekdayName.string(from: self)
}
var monthName: String {
return Formatter.month.string(from: self)
}
}
extension String {
var customDate: Date? {
return Formatter.customDate.date(from: self)
}
}
pemakaian:
// this will be displayed like this regardless of the user and system preferences
Date().customTime // "16:50"
Date().customDate // "06/05/17"
// this will be displayed according to user and system preferences
Date().weekdayName // "Saturday"
Date().monthName // "May"
Memisahkan tanggal khusus dan mengonversi tanggal kembali ke format string yang sama:
let dateString = "01/02/10"
if let date = dateString.customDate {
print(date.customDate) // "01/02/10\n"
print(date.monthName) // customDate
}
Ini dia semua elemen yang bisa Anda gunakan untuk menyesuaikannya seperlunya:
Mengapa tidak menambahkan kategori ke NSString?
// NSString+Date.h
@interface NSString (Date)
+ (NSDate*)stringDateFromString:(NSString*)string;
+ (NSString*)stringDateFromDate:(NSDate*)date;
@end
// NSString+Date.m
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];
NSDate *date = [dateFormatter dateFromString:stringDate ];
[dateFormatter release];
+ (NSDateFormatter*)stringDateFormatter
{
static NSDateFormatter* formatter = nil;
if (formatter == nil)
{
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];
}
return formatter;
}
+ (NSDate*)stringDateFromString:(NSString*)string
{
return [[NSString stringDateFormatter] dateFromString:string];
}
+ (NSString*)stringDateFromDate:(NSDate*)date
{
return [[NSString stringDateFormatter] stringFromDate:date];
}
// Usage (#import "NSString+Date.h") or add in "YOUR PROJECT".pch file
NSString* string = [NSString stringDateFromDate:[NSDate date]];
NSDate* date = [NSString stringDateFromString:string];
menggunakan "10" untuk mewakili satu tahun tidak baik, karena itu bisa 1910, 1810, dll. Anda mungkin harus menggunakan 4 digit untuk itu.
Jika Anda dapat mengubah tanggal menjadi sesuatu seperti
yyyymmdd
Maka Anda dapat menggunakan:
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];
// Convert date object to desired output format
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
dateStr = [dateFormat stringFromDate:date];
[dateFormat release];
// Convert string to date
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:dateStr];
// Convert Date to string
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
dateStr = [dateFormat stringFromDate:date];
[dateFormat release];
NSString *mystr=@"Your string date";
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [dateFormatter dateFromString:mystr];
Nslog(@"%@",now);
Jika Anda ingin mengatur format gunakan kode di bawah ini:
NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is important - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];
Nslog(@"%@",[dateFormatter dateFromString:dateString]);
Gunakan metode ini untuk mengonversi dari NSString
ke NSdate
:
-(NSDate *)getDateFromString:(NSString *)pstrDate
{
NSDateFormatter* myFormatter = [[NSDateFormatter alloc] init];
[myFormatter setDateFormat:@"dd/MM/yyyy"];
NSDate* myDate = [myFormatter dateFromString:pstrDate];
return myDate;
}
Jika ada orang yang tertarik melakukan sesuatu seperti ini di Swift akhir-akhir ini, saya mulai dengan sesuatu, meskipun itu tidak sempurna.
func detectDate(dateString: NSString) -> NSDate {
var error: NSError?
let detector: NSDataDetector = NSDataDetector.dataDetectorWithTypes(NSTextCheckingType.Date.toRaw(), error: &error)!
if error == nil {
var matches = detector.matchesInString(dateString, options: nil, range: NSMakeRange(0, dateString.length))
let currentLocale = NSLocale.currentLocale()
for match in matches {
match.resultType == NSTextCheckingType.Date
NSLog("Date: \(match.date.description)")
return match.date
}
}
return NSDate()
}
Tanggal untuk NSString
NSString *dateString = [NSString stringWithFormat:@"%@",[NSDate date]];
NSLog(@"string: %@",dateString ); //2015-03-24 12:28:49 +0000
NSString ke NSDate
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSDate *date = [formatter dateFromString:dateString];
NSLog(@"date: %@", date); //015-03-24 12:28:49 +0000
Anda dapat menggunakan ekstensi untuk ini.
extension NSDate {
//NSString to NSDate
convenience
init(dateString:String) {
let nsDateFormatter = NSDateFormatter()
nsDateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
// Add the locale if required here
let dateObj = nsDateFormatter.dateFromString(dateString)
self.init(timeInterval:0, sinceDate:dateObj!)
}
//NSDate to time string
func getTime() -> String {
let timeFormatter = NSDateFormatter()
timeFormatter.dateFormat = "hh:mm"
//Can also set the default styles for date or time using .timeStyle or .dateStyle
return timeFormatter.stringFromDate(self)
}
//NSDate to date string
func getDate() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd, MMM"
return dateFormatter.stringFromDate(self)
}
//NSDate to String
func getString() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
return dateFormatter.stringFromDate(self)
}
}
Jadi sementara eksekusi kode aktual akan terlihat seperti berikut
var dateObjFromString = NSDate(dateString: cutDateTime)
var dateString = dateObjFromString.getDate()
var timeString = dateObjFromString.getTime()
var stringFromDate = dateObjFromString.getString()
Ada beberapa metode standar juga tapi saya kira itu mungkin tidak berfungsi untuk format yang Anda berikan dari dokumentasi
-dateFromString(_:)
-stringFromDate(_:)
-localizedStringFromDate(_ date: NSDate,
dateStyle dateStyle: NSDateFormatterStyle,
timeStyle timeStyle: NSDateFormatterStyle) -> String
Praktik terbaik adalah membangun sendiri kelas umum tempat Anda meletakkan semua metode penggunaan umum, metode yang berguna di hampir semua proyek dan menambahkan kode yang disarankan oleh @Pavan sebagai:
+ (NSDate *)getDateOutOfString:(NSString *)passedString andDateFormat:(NSString *)dateFormat{
NSString *dateString = passedString;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:dateFormat];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
return dateFromString;
}
.. dan seterusnya untuk semua metode bermanfaat lainnya
Dengan melakukannya, Anda mulai membuat kode yang dapat digunakan kembali yang bersih untuk aplikasi Anda. Bersulang!
Sesuai Swift 2.2
Anda bisa mendapatkan NSDate dengan mudah dari String dan String dari NSDate. misalnya
Pengaturan format tanggal pertama
let formatter = NSDateFormatter();
formatter.dateStyle = NSDateFormatterStyle.MediumStyle
formatter.timeStyle = .NoStyle
formatter.dateFormat = "MM/dd/yyyy"
Sekarang dapatkan tanggal dari string dan sebaliknya.
let strDate = formatter.stringFromDate(NSDate())
print(strDate)
let dateFromStr = formatter.dateFromString(strDate)
print(dateFromStr)
Sekarang nikmati.
NSString ke NSDate atau NSDate ke NSString
//This method is used to get NSDate from string
//Pass the date formate ex-"dd-MM-yyyy hh:mm a"
+ (NSDate*)getDateFromString:(NSString *)dateString withFormate:(NSString *)formate {
// Converted date from date string
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
[dateFormatter setDateFormat:formate];
NSDate *convertedDate = [dateFormatter dateFromString:dateString];
return convertedDate;
}
//This method is used to get the NSString for NSDate
//Pass the date formate ex-"dd-MM-yyyy hh:mm a"
+ (NSString *)getDateStringFromDate:(NSDate *)date withFormate:(NSString *)formate {
// Converted date from date string
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
[dateFormatter setDateFormat:formate];
NSString *convertedDate = [dateFormatter stringFromDate:date];
return convertedDate;
}
Contoh di atas tidak hanya ditulis untuk Swift 3.0+
Perbarui - Swift 3.0+ - Konversi Tanggal Ke String
let date = Date() // insert your date data here
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" // add custom format if you'd like
var dateString = dateFormatter.string(from: date)
String To Date
var dateFormatter = DateFormatter()
dateFormatter.format = "dd/MM/yyyy"
var dateFromString: Date? = dateFormatter.date(from: dateString) //pass string here
Date To String
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let newDate = dateFormatter.string(from: date) //pass Date here