格式化字符串中的日期

发布于 2024-09-03 11:36:51 字数 189 浏览 4 评论 0原文

我正在尝试将日期从字符串格式化为另一种格式。

例如:将 2012-05-29 23:55:52 转换为 29/05 *newline* 2010

我认为我只是不明白 NSDate 和 NSDateFormatter 背后的逻辑..

任何帮助将不胜感激。谢谢 :)

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 NSDate and NSDateFormatter, I think..

Any help will be appreciated. Thanks :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

漫雪独思 2024-09-10 11:36:51

您将需要创建一个 NSDateFormatter,然后将其 dateFormat 设置为匹配您拥有的第一个日期,例如:

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

这将设置您的日期格式化程序以识别您的日期字符串。然后,您可以使用此方法获取 NSDate 对象。

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

这将为您提供表示该日期的完整 NSDate 对象。现在您需要重新格式化日期并将其转回字符串,因此将格式化程序上的 dateFormat 设置为新格式​​,并获取返回日期的新字符串表示形式:

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

瞧!你有新的约会对象了:)

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 :)

ζ澈沫 2024-09-10 11:36:51

如果您只进行简单的字符串处理,则实际上不需要遍历日期对象。

 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)

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)
世界和平 2024-09-10 11:36:51

请查找以下代码将日期从一种格式转换为另一种格式。它将给出您当前区域的时间。

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

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 ""
    }
}
那一片橙海, 2024-09-10 11:36:51

对于那些喜欢使用扩展的人。

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

使用:

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

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")
幻想少年梦 2024-09-10 11:36:51

JFrank 的回答很好。但苹果表示:

“缓存格式化程序以提高效率”(https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html)以无效分配和丢弃。
因此,由于静态已经很懒惰了......

(为了清楚起见,我仅显示生成日期......输出格式类似......)

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

     }


}

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

     }


}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文