开发者

Format a date from a string

I'm trying to format a date from a string into another format.

For example: 2012-05-29 23:55:52 into 29/05 *newline* 2010.

I just don't get the logics behind 开发者_Python百科NSDate and NSDateFormatter, I think..

Any help will be appreciated. Thanks :)


You will need to create an NSDateFormatter, and then set it's dateFormat to match the first date you have, eg:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

That will set your date formatter to recognise your date string. You can then obtain an NSDate object from this using

NSDate *myDate = [dateFormatter dateFromString:myDateString]; // myDateString is the 2012-05-29 23:55:52 string

This gives you a full NSDate object representing that date. Now you need to reformat the date and turn it back into a string, so set the dateFormat on your formatter to the new format, and get a new string representation of the returned date:

[dateFormatter setDateFormat:@"dd/MM\nyyyy"];
NSString *newlyFormattedDateString = [dateFormatter stringFromDate:myDate];
[dateFormatter release], dateFormatter = nil;

And voila! You have your new date :)


If you're only doing simple string processing, Going through a date object is not really needed.

 let dateString = "2012-05-29 23:55:52"
 let dateParts = dateString.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "- :")) 
 let newDateString = "\(dateParts[2])/\(dateParts[1])\n\(dateParts[0])"

 print(newDateString)


Please find following code to convert date from one format to another format. It will give time in your current zone.

func convertDateFormat(sourceString : String, sourceFormat : String, destinationFormat : String) -> String{

    let dateFormatter = DateFormatter();
    dateFormatter.dateFormat = sourceFormat;

    if let date = dateFormatter.date(from: sourceString){
        dateFormatter.dateFormat = destinationFormat;
        return dateFormatter.string(from: date)
    }else{
        return ""
    }
}


For those who prefer to use extension.

extension String {
func formattedDate(inputFormat: String, outputFormat: String) -> String {
    let inputFormatter = DateFormatter()
    inputFormatter.dateFormat = inputFormat

    if let date = inputFormatter.date(from: self) {
        let outputFormatter = DateFormatter()
        outputFormatter.dateFormat = outputFormat
        return outputFormatter.string(from: date)
    } else {
        return self  // If the string is not in the correct format, we return it without formatting
    }
}

Use:

tfDate.text = strDate.formattedDate(inputFormat: "yyyy-MM-dd", outputFormat: "dd/MM/yyyy")


JFrank answer is good. But Apple says:

"Cache Formatters for Efficiency" (https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html) to void allocating and discarding. So, as statics are already lazy...

(For clarity I show only generating a date.. output format is similar..)

import Foundation


extension Date{


    // Global constants and variables are always computed lazily:
    static private var yyyyMMdd_dateFormatter : DateFormatter  {
        let df = DateFormatter()
        df.dateFormat = "yyyyMMdd"
        return df
    }


    init?(YYYYMMDDString: String?){

        guard let dateString = YYYYMMDDString else {return nil}

        guard let date = Self.yyyyMMdd_dateFormatter.date(from: dateString) else {
            return nil
        }
            self = date

     }


}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜