获取时间戳格式的当前 NSDate

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

这是我的代码:

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

有没有可能使用 NSDateFormatter将“ result 字符串”更改为一个时间戳?

155931 次浏览

使用 [[NSDate date] timeIntervalSince1970]

以下是我的方法:

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是将时间戳转换为毫秒。如果您喜欢以秒为单位的时间间隔,则可以删除此选项。

斯威夫特

如果您想在 Swift 中使用全局变量,可以使用以下命令:

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

然后,你就可以宣布死亡了

println("Timestamp: \(Timestamp)")

同样,*1000是以毫秒为单位的,如果您愿意,可以删除它。如果你想保持它作为一个 NSTimeInterval

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

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

- (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 时间。

//下面的方法将在转换为毫秒后返回您的时间戳

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

如果您希望直接在 NSDate 对象上调用这个方法,并以毫秒为单位获取时间戳,而不需要小数点后面的位置,那么可以将这个方法定义为一个类别:

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

也可以用

@(time(nil)).stringValue);

以秒为单位的时间戳。

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

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

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

斯威夫特:

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

}

    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);

日志将是: filename:/Users/Shared/Recoring _ 06-28-201612:53:26. mov

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

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

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