2015-05-24 101 views
-3
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
[dateFormat setDateFormat:@"dd/MM/yyyy"]; 
NSString *theDate = [dateFormat stringFromDate:date]; 
time_t unixTime = (time_t) [date timeIntervalSince1970]; 

我需要unixTime不小時,分鐘和秒的iOS獲取時間戳沒有小時和分鐘和秒

+0

你所說的「無時,分,秒」是什麼意思?你的意思是指在當天所有時間都是折扣的秒數?所以基本上直到剛剛過去的午夜? –

回答

0

您可能希望從原來的日期提取顯著日期組件

NSDate *date = [NSDate date]; 

NSCalendar *gregorianCalendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian]; 

NSDateComponents *componentsDate = [gregorianCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date]; 

然後,與他們建立新的約會

NSDateComponents *toDateComponents = [NSDateComponents new]; 
[toDateComponents setYear:[componentsDate year]]; 
[toDateComponents setMonth:[componentsDate month]]; 
[toDateComponents setDay:[componentsDate day]]; 
[toDateComponents setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; 

NSDate *toDate = [gregorianCalendar dateFromComponents:toDateComponents]; 

最後,得到時間間隔

NSTimeInterval toDateTimeInterval = [toDate timeIntervalSince1970]; 
0

或者它從另一個方向過來,在斯威夫特:

// Get the current date and time 
let theDate = NSDate() 

// Get the current hours, minutes and seconds from "now" 
let theCalendar = NSCalendar.currentCalendar() 
let theComponents = theCalendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond, fromDate: theDate) 

// Construct a new time, the equivalent number of seconds earlier than "now". This is effectively midnight that passed 
let theCorrectedDate = NSDate(timeInterval: -(NSTimeInterval)((theComponents.hour * 3600) + (theComponents.minute * 60) + theComponents.second), sinceDate: theDate) 

// And that gives you the unix time you want 
let theUnixTime = theCorrectedDate.timeIntervalSince1970 
相關問題