获取时间戳格式的当前NSDate


83

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

这是我的代码:

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

是否可以NSDateFormatter将'resultString'更改为时间戳?

Answers:


216

这是我使用的:

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
}

在任何类的上下文之外声明这些内容,并且可以在任何地方访问它们。


2
没问题,我更新了我使用的宏,以防它对您的情况有所帮助!
罗根

3
谢谢@Logan,但我很确定总是不鼓励使用宏。您很容易失去对使用宏的大程序的理解。最好只创建一个执行此操作并在需要时调用的方法。
Supertecnoboff 2014年

顺便说一句-如果您要将值添加到字典中,则可以执行以下操作:@{@"timestamp": @([[NSDate date] timeIntervalSince1970])
Cbas 2016年

15

使用 [[NSDate date] timeIntervalSince1970]


8
@([[NSDate date] 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时间。


您的GetCurrentTimeStamp()有几个小写问题。剪切并粘贴到Xcode中以查看
tdios'1

请使用此“ NSString * strTimeStamp = [NSString stringWithFormat:@”%lld“,毫秒]; NSLog(@”时间戳为=%@“,strTimeStamp);”
Vicky,2015年

6

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

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

1

//以下方法将转换为毫秒后返回时间戳。[返回STRING]

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

1

也可以使用

@(time(nil)).stringValue);

以秒为单位的时间戳。


1

定义宏以获取当前时间戳很方便

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

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


0

迅速:

我有一个UILabel,它在Camera Preview上显示TimeStamp。

    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 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)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.