【问题标题】:Get current NSDate in timestamp format以时间戳格式获取当前 NSDate
【发布时间】:2014-04-17 00:49:27
【问题描述】:

我有一个获取当前时间并将其设置为字符串的基本方法。但是,如何让它以 UNIX 自 1970 年以来的时间戳格式格式化当前日期和时间?

这是我的代码:

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

是否可以使用NSDateFormatter 将“resultString”更改为时间戳?

【问题讨论】:

    标签: cocoa cocoa-touch nsdate nsdateformatter unix-timestamp


    【解决方案1】:

    这是我使用的:

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

    作为时间间隔

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

    注意:

    1000 是将时间戳转换为毫秒。如果您希望 timeInterval 以秒为单位,您可以删除它。

    斯威夫特

    如果你想在 Swift 中使用一个全局变量,你可以使用这个:

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

    那么,你就可以调用它了

    println("Timestamp: \(Timestamp)")
    

    同样,*1000 表示毫秒,如果您愿意,可以将其删除。如果您想将其保留为NSTimeInterval

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

    在任何类的上下文之外声明它们,它们将可以在任何地方访问。

    【讨论】:

    • 没问题,我更新了我使用的宏,以防它对您的情况有所帮助!
    • 感谢@Logan,但我很确定宏总是不受欢迎的。您很容易失去对带有宏的大程序的理解。最好只创建一个方法来执行此操作并在需要时调用它。
    • 顺便说一句 - 如果您要将值添加到字典中,您可以这样做:@{@"timestamp": @([[NSDate date] timeIntervalSince1970])
    【解决方案2】:

    使用[[NSDate date] timeIntervalSince1970]

    【讨论】:

    • @([[NSDate date] timeIntervalSince1970]).stringValue
    【解决方案3】:
    - (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 时间。

    【讨论】:

    • 您的 GetCurrentTimeStamp() 有几个小写问题。剪切并粘贴到 Xcode 中查看
    • 请使用这个 "NSString *strTimeStamp = [NSString stringWithFormat:@"%lld",milliseconds]; NSLog(@"The Timestamp is = %@",strTimeStamp);"
    【解决方案4】:

    如果您想直接在 NSDate 对象上调用此方法并以字符串形式获取时间戳(以毫秒为单位,不带任何小数位),请将此方法定义为类别:

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

    【讨论】:

      【解决方案5】:

      // 以下方法将在转换为毫秒后返回您的时间戳。 [返回字符串]

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

      【讨论】:

        【解决方案6】:

        也可以用

        @(time(nil)).stringValue);
        

        以秒为单位的时间戳。

        【讨论】:

          【解决方案7】:

          定义一个宏来获取当前时间戳很方便

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

          那么你可以使用let timestamp = Constant.Time.now()

          【讨论】:

            【解决方案8】:

            斯威夫特:

            我有一个 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)
            

            }

            【讨论】:

              【解决方案9】:
                  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);
              

              日志将是:文件名:/Users/Shared/Recording_06-28-2016 12:53:26.mov

              【讨论】:

                【解决方案10】:

                如果您需要时间戳作为字符串。

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

                【讨论】:

                  【解决方案11】:

                  从 NSDate Swift 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)
                  

                  【讨论】:

                    猜你喜欢
                    • 2021-12-04
                    • 2018-08-16
                    • 2020-08-09
                    • 2011-12-26
                    • 1970-01-01
                    • 1970-01-01
                    • 2014-05-28
                    • 1970-01-01
                    • 2011-09-18
                    相关资源
                    最近更新 更多