2014-03-12 36 views
80

我有一個基本的方法獲取當前時間並將其設置爲一個字符串。但是,如何在UNIX自1970年以後的時間戳格式中將其格式化爲當前日期&?獲取時間戳格式的當前NSDate

這裏是我的代碼:

NSDate *currentTime = [NSDate date]; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"hh-mm"]; 
NSString *resultString = [dateFormatter stringFromDate: currentTime]; 

是否有可能使用NSDateFormatter改變「resultString」成時間戳?

回答

207

這是我使用:

NSString * timestamp = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000]; 

(毫秒時間1000,否則,採取了)

如果你使用它的時候,它可能很高興宣佈一個宏

#define TimeStamp [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000] 

然後調用它是這樣的:

NSString * timestamp = TimeStamp; 

或方法:

- (NSString *) timeStamp { 
    return [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000]; 
} 

由於TimeInterval所

- (NSTimeInterval) timeStamp { 
    return [[NSDate date] timeIntervalSince1970] * 1000; 
} 

注:

的1000是時間戳轉換爲毫秒。如果你喜歡你的timeInterval(秒),你可以刪除它。

斯威夫特

如果您想在斯威夫特一個全局變量,你可以這樣做:

var Timestamp: String { 
    return "\(NSDate().timeIntervalSince1970 * 1000)" 
} 

然後,你可以把它叫做

println("Timestamp: \(Timestamp)") 

再次, *1000爲毫秒,如果你願意,你可以刪除它。如果你想保持它作爲一個NSTimeInterval

var Timestamp: NSTimeInterval { 
    return NSDate().timeIntervalSince1970 * 1000 
} 

這些聲明的任何類的內容以外,他們會在任何地方訪問。

+2

沒問題,我更新了我使用的宏,以防它對您的情況有所幫助! – Logan

+3

感謝@Logan,但我非常肯定,宏的總是不鼓勵。用宏可以很容易地失去對大程序的理解。最好只是製作一個方法,並在需要時調用它。 – Supertecnoboff

+0

@Supertecnoboff你覺得這樣的作品? – 2015-04-22 12:14:14

15

使用[[NSDate date] timeIntervalSince1970]

+7

'@([NSDate的日期] timeIntervalSince1970])。stringValue' – mattsven

7
- (void)GetCurrentTimeStamp 
    { 
     NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init]; 
     [objDateformat setDateFormat:@"yyyy-MM-dd"]; 
     NSString *strTime = [objDateformat stringFromDate:[NSDate date]]; 
     NSString *strUTCTime = [self GetUTCDateTimeFromLocalTime:strTime];//You can pass your date but be carefull about your date format of NSDateFormatter. 
     NSDate *objUTCDate = [objDateformat dateFromString:strUTCTime]; 
     long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0); 

     NSString *strTimeStamp = [NSString stringWithFormat:@"%lld",milliseconds]; 
NSLog(@"The Timestamp is = %@",strTimeStamp); 
    } 

- (NSString *) GetUTCDateTimeFromLocalTime:(NSString *)IN_strLocalTime 
    { 
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
     [dateFormatter setDateFormat:@"yyyy-MM-dd"]; 
     NSDate *objDate = [dateFormatter dateFromString:IN_strLocalTime]; 
     [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; 
     NSString *strDateTime = [dateFormatter stringFromDate:objDate]; 
     return strDateTime; 
    } 

注意: - 時間戳必須在UTC區域,因此我將本地時間轉換爲UTC時間。

+1

+1關於UTC時區的注意事項。 –

+0

您的GetCurrentTimeStamp()有幾個小寫字母問題。剪切並粘貼到Xcode中以查看 – tdios

+0

請使用此「NSString * strTimeStamp = [NSString stringWithFormat:@」%lld「,毫秒]; NSLog(@」The Timestamp is =%@「,strTimeStamp);」 – Vicky

1

//以下方法會在轉換爲毫秒後返回時間戳。[返回String]

- (NSString *) timeInMiliSeconds 
{ 
    NSDate *date = [NSDate date]; 
    NSString * timeInMS = [NSString stringWithFormat:@"%lld", [@(floor([date timeIntervalSince1970] * 1000)) longLongValue]]; 
    return timeInMS; 
} 
4

如果你想直接調用一個NSDate對象上此方法,並得到了時間戳以毫秒爲單位的字符串沒有任何小數位,定義該方法爲一類:

@implementation NSDate (MyExtensions) 
- (NSString *)unixTimestampInMilliseconds 
{ 
    return [NSString stringWithFormat:@"%.0f", [self timeIntervalSince1970] * 1000]; 
} 
1

也可以用

@(time(nil)).stringValue); 

的時間戳秒。

1

可方便快捷地定義一個宏得到當前時間戳

class Constant { 
    struct Time { 
     let now = { round(NSDate().timeIntervalSince1970) } // seconds 
    } 
} 

然後你可以使用let timestamp = Constant.Time.now()

0

斯威夫特:

我有一個UILabel表示時間戳在攝像頭預覽。

var timeStampTimer : NSTimer? 
    var dateEnabled: Bool? 
    var timeEnabled: Bool? 
    @IBOutlet weak var timeStampLabel: UILabel! 

override func viewDidLoad() { 
     super.viewDidLoad() 
//Setting Initial Values to be false. 
     dateEnabled = false 
     timeEnabled = false 
} 

override func viewWillAppear(animated: Bool) { 

     //Current Date and Time on Preview View 
     timeStampLabel.text = timeStamp 
     self.timeStampTimer = NSTimer.scheduledTimerWithTimeInterval(1.0,target: self, selector: Selector("updateCurrentDateAndTimeOnTimeStamperLabel"),userInfo: nil,repeats: true) 
} 

func updateCurrentDateAndTimeOnTimeStamperLabel() 
    { 
//Every Second, it updates time. 

     switch (dateEnabled, timeEnabled) { 
     case (true?, true?): 
      timeStampLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .LongStyle, timeStyle: .MediumStyle) 
      break; 
     case (true?, false?): 
      timeStampLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .LongStyle, timeStyle: .NoStyle) 
      break; 

     case (false?, true?): 
      timeStampLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyle, timeStyle: .MediumStyle) 
      break; 
     case (false?, false?): 
      timeStampLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyle, timeStyle: .NoStyle) 
      break; 
     default: 
      break; 

     } 
    } 

我正在設置一個按鈕來觸發一個alertView。

@IBAction func settingsButton(sender : AnyObject) { 


let cameraSettingsAlert = UIAlertController(title: NSLocalizedString("Please choose a course", comment: ""), message: NSLocalizedString("", comment: ""), preferredStyle: .ActionSheet) 

let timeStampOnAction = UIAlertAction(title: NSLocalizedString("Time Stamp on Photo", comment: ""), style: .Default) { action in 

    self.dateEnabled = true 
    self.timeEnabled = true 

} 
let timeStampOffAction = UIAlertAction(title: NSLocalizedString("TimeStamp Off", comment: ""), style: .Default) { action in 

    self.dateEnabled = false 
    self.timeEnabled = false 

} 
let dateOnlyAction = UIAlertAction(title: NSLocalizedString("Date Only", comment: ""), style: .Default) { action in 

    self.dateEnabled = true 
    self.timeEnabled = false 


} 
let timeOnlyAction = UIAlertAction(title: NSLocalizedString("Time Only", comment: ""), style: .Default) { action in 

    self.dateEnabled = false 
    self.timeEnabled = true 
} 

let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel) { action in 

} 
cameraSettingsAlert.addAction(cancel) 
cameraSettingsAlert.addAction(timeStampOnAction) 
cameraSettingsAlert.addAction(timeStampOffAction) 
cameraSettingsAlert.addAction(dateOnlyAction) 
cameraSettingsAlert.addAction(timeOnlyAction) 

self.presentViewController(cameraSettingsAlert, animated: true, completion: nil) 

}

0
NSDate *todaysDate = [NSDate new]; 
NSDateFormatter *formatter = [NSDateFormatter new]; 
[formatter setDateFormat:@"MM-dd-yyyy HH:mm:ss"]; 
NSString *strDateTime = [formatter stringFromDate:todaysDate]; 

NSString *strFileName = [NSString stringWithFormat:@"/Users/Shared/Recording_%@.mov",strDateTime]; 
NSLog(@"filename:%@",strFileName); 

日誌將是:文件名:/用戶/共享/ Recording_06-28-2016 12:53:26.mov

0

如果需要時間戳作爲字符串。

time_t result = time(NULL);     
NSString *timeStampString = [@(result) stringValue]; 
0

從NSDate的斯威夫特得到時間戳3

func getCurrentTimeStampWOMiliseconds(dateToConvert: NSDate) -> String { 
    let objDateformat: DateFormatter = DateFormatter() 
    objDateformat.dateFormat = "yyyy-MM-dd HH:mm:ss" 
    let strTime: String = objDateformat.string(from: dateToConvert as Date) 
    let objUTCDate: NSDate = objDateformat.date(from: strTime)! as NSDate 
    let milliseconds: Int64 = Int64(objUTCDate.timeIntervalSince1970) 
    let strTimeStamp: String = "\(milliseconds)" 
    return strTimeStamp 
} 

要使用

let now = NSDate() 
let nowTimeStamp = self.getCurrentTimeStampWOMiliseconds(dateToConvert: now)