IOS-時間與字串互相轉換

來源:互聯網
上載者:User

IOS-時間與字串互相轉換

有時會遇到這樣的問題,需要把時間和時間戳記互相轉換

比如把目前時間轉換成 “20140716155436”這樣的格式

或者是把“20140716155436”轉換成“2014-07-16 15:54:36”

首先來第一個:

目前時間轉換成 “20140716155436”這樣的格式

///////////////////////////////

//擷取目前時間

NSDate * today = [NSDatedate];

NSLog(@"%@",today);

列印出來是“2014-07-16 07:54:36 +0000”

很奇怪?現在明明是2014-07-16 15:54:36啊

因為存在不同時區,系統預設格林尼治時間

所以就要轉換時間格式了

//轉換時間格式

NSDateFormatter *df = [[NSDateFormatteralloc] init];//格式化

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

NSString * s1 = [df stringFromDate:today];

NSLog(@" s1s1s1s%@",s1);

列印出來是“2014-07-16 15:54:36”

現在已經擷取到當前的時間

這樣還沒有完呢,需要轉換成一個字串,類似“20140716052021”的時間戳記


NSDate * date = [df dateFromString:s1];

//轉換時間格式

NSDateFormatter *df2 = [[NSDateFormatteralloc] init];//格式化

[df2 setDateFormat:@"yyyyMMddHHmmss"];

[df2 setLocale:[[NSLocalealloc] initWithLocaleIdentifier:@"zh_CN"]];

NSLog(@"%@",[df2stringFromDate:date]);

列印出來是“20140716155436”
接下來就是第二個:

把“20140716155436”轉換成“2014-07-16 15:54:36”

首先要把20140716155436轉換成時間格式

//轉換時間格式

NSDateFormatter *df = [[NSDateFormatteralloc] init];//格式化

[df setDateFormat:@"yyyyMMddHHmmss"];

[df setLocale:[[NSLocalealloc] initWithLocaleIdentifier:@"zh_CN"] ];

NSDate *date =[[NSDatealloc]init];

date =[dfdateFromString:bill_timeStr];

str = [NSStringstringWithFormat:@"%@",date];

str的結果是“2014-07-16 07:54:36 +0000”

這時候就需要再轉一次

//

NSDateFormatter * df2 = [[NSDateFormatteralloc] init];

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

NSString * str1 = [df2 stringFromDate:date];

str1的結果是“2014-07-16 15:54:36”

ok,大功告成


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.