2013-04-18 160 views
-2

我正在寫iPhone應用程序。 我想按照以下格式獲取當前的日期和時間。獲取特殊格式的當前日期字符串

Thu, 18 Apr 2013 01:41:13 

我該如何做到這一點?

+0

你有沒有努力使用'NSDateFormatter'?你有什麼嘗試? – rmaddy 2013-04-18 03:16:11

+0

當然,我嘗試使用NSDateFormatter。但是我怎麼能得到月和星期的字符串? – ttotto 2013-04-18 03:20:37

+0

發佈你到目前爲止所以人們可以幫助丟失的部分。 – rmaddy 2013-04-18 03:21:19

回答

1

documentation for setDateFormat: in the NSDateFormatter Class Reference鏈接到Data Formatting Guide

數據格式指南中,Date Formatters > Use Format Strings to Specify Custom Formats > Fixed Formats部分鏈接到Appendix F of the *Unicode Technical Standard #35

附錄F,而有些鈍,告訴你一切:

  • 使用E爲短工作日名稱。
  • 本月的日子使用d
  • 使用MMM作爲短月份名稱。
  • 年度使用y
  • 使用hh小時。
  • 使用mm分鐘。
  • 第二次使用ss

我們可以快速測試,而不需要寫使用Python的Cocoa綁定一個整體的Objective-C程序:

:; python 
Python 2.7.2 (default, Oct 11 2012, 20:14:37) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> from Cocoa import * 
>>> f = NSDateFormatter.new()   
>>> f.setDateFormat_('E, d MMM y hh:mm:ss') 
>>> f.stringFromDate_(NSDate.new()) 
u'Wed, 17 Apr 2013 10:40:25' 

在Objective-C,它看起來像這樣:

NSDateFormatter *f = [NSDateFormatter new]; 
f.dateFormat = @"E, d MMM y hh:mm:ss"; 
NSLog(@"%@", [f stringFromDate:[NSDate new]]); 

注意創建一個NSDateFormatter是昂貴的。如果您要格式化許多日期,您應該創建一次並保留它。

+0

非常感謝。它適用於我。你真好! – ttotto 2013-04-18 03:43:26

+0

對此還有一個問題。我的手機區域格式不是美國的,所以我可以獲得非美式格式的dateformat字符串。但我需要美國風格的日期。我怎樣才能得到這個? – ttotto 2013-04-18 08:47:59

+1

查看' - [NSDateFormatter setLocale:]'方法的文檔。按照指向'NSLocale'的鏈接。讀。 – 2013-04-18 18:59:22

相關問題