타임 스탬프 형식으로 현재 NSDate 가져 오기
현재 시간을 가져 와서 문자열로 설정하는 기본 방법이 있습니다. 그러나 1970 년 이후의 UNIX 타임 스탬프 형식으로 현재 날짜 및 시간을 형식화하려면 어떻게해야합니까?
내 코드는 다음과 같습니다.
NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh-mm"];
NSString *resultString = [dateFormatter stringFromDate: currentTime];
NSDateFormatter
'resultString'을 타임 스탬프로 변경하는 데 사용할 수 있습니까?
내가 사용하는 것은 다음과 같습니다.
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을 초 단위로 선호하는 경우이를 제거 할 수 있습니다.
빠른
Swift에서 전역 변수를 원하면 다음을 사용할 수 있습니다.
var Timestamp: String {
return "\(NSDate().timeIntervalSince1970 * 1000)"
}
그런 다음 호출 할 수 있습니다.
println("Timestamp: \(Timestamp)")
다시 말하지만, *1000
밀리 초 단위이며 원하는 경우 제거 할 수 있습니다. 당신이 그것을 유지하고 싶다면NSTimeInterval
var Timestamp: NSTimeInterval {
return NSDate().timeIntervalSince1970 * 1000
}
클래스의 컨텍스트 외부에서 선언하면 어디서나 액세스 할 수 있습니다.
사용하다 [[NSDate date] timeIntervalSince1970]
- (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 시간으로 변환합니다.
NSDate 객체에서 직접이 메서드를 호출하고 소수점 이하 자릿수없이 밀리 초 단위의 문자열로 타임 스탬프를 가져 오려면이 메서드를 범주로 정의합니다.
@implementation NSDate (MyExtensions)
- (NSString *)unixTimestampInMilliseconds
{
return [NSString stringWithFormat:@"%.0f", [self timeIntervalSince1970] * 1000];
}
// 다음 메서드는 밀리 초로 변환 한 후 타임 스탬프를 반환합니다. [반환 문자열]
- (NSString *) timeInMiliSeconds
{
NSDate *date = [NSDate date];
NSString * timeInMS = [NSString stringWithFormat:@"%lld", [@(floor([date timeIntervalSince1970] * 1000)) longLongValue]];
return timeInMS;
}
또한 사용할 수 있습니다
@(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);
Log will be : filename:/Users/Shared/Recording_06-28-2016 12:53:26.mov
If you need time stamp as a string.
time_t result = time(NULL);
NSString *timeStampString = [@(result) stringValue];
To get timestamp from 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
}
To use
let now = NSDate()
let nowTimeStamp = self.getCurrentTimeStampWOMiliseconds(dateToConvert: now)
참고URL : https://stackoverflow.com/questions/22359090/get-current-nsdate-in-timestamp-format
'program story' 카테고리의 다른 글
CSS를 사용하여 셀 사이에 공백 추가 (td) (0) | 2020.09.21 |
---|---|
jQuery 플러그인 : 콜백 기능 추가 (0) | 2020.09.21 |
배열을 N 길이의 청크로 분할 (0) | 2020.09.20 |
ES6 구문을 사용하여 onclick 이벤트를 통해 매개 변수를 전달하는 반응 (0) | 2020.09.20 |
GDB가 줄 사이를 예측할 수없이 점프하고 변수를“ (0) | 2020.09.20 |