如何将任何给定日期转换为毫秒?例如,2014-01-23到时间戳转换。
NSDate *date = [dateFormatter dateFromString:@"2014-01-23"];
NSLog(@"date=%@",date);
NSTimeInterval interval = [date timeIntervalSince1970];
NSLog(@"interval=%f",interval);
NSDate *methodStart = [NSDate dateWithTimeIntervalSince1970:interval];
[dateFormatter setDateFormat:@"yyyy/mm/dd "];
NSLog(@"result: %@", [dateFormatter stringFromDate:methodStart]);
输出结果:1970/30/01
答案 0 :(得分:6)
试一试。 “mm”代表分钟,而“MM”代表月份。
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init] ;
[dateFormatter setDateFormat:@"yyyy-MM-dd"] ;
NSDate *date = [dateFormatter dateFromString:@"2014-01-23"] ;
NSLog(@"date=%@",date) ;
NSTimeInterval interval = [date timeIntervalSince1970] ;
NSLog(@"interval=%f",interval) ;
NSDate *methodStart = [NSDate dateWithTimeIntervalSince1970:interval] ;
[dateFormatter setDateFormat:@"yyyy/MM/dd "] ;
NSLog(@"result: %@", [dateFormatter stringFromDate:methodStart]) ;
答案 1 :(得分:3)
将当前日期/时间转换为时间戳:
// current date and time
let someDate = Date()
// time interval since 1970
let myTimeStamp = someDate.timeIntervalSince1970
另见
答案 2 :(得分:0)
NSTimeinterval实际上是一个双倍的,从特定日期开始是秒(在你的情况下,1970年的开始)
答案 3 :(得分:0)
[date1 timeIntervalSinceDate:date2]
将从两个NSDate对象返回秒数。
double seconds = [date1 timeIntervalSinceDate:date2];
double milliSecondsPartOfCurrentSecond = seconds - [seconds intValue];
milliSecondsPartOfCurrentSecond
答案 4 :(得分:0)
注意: - UNIX时间戳格式包含13位数,因此我们需要与结果进行1000次乘法运算。 时间戳必须是UTC ZONE而不是我们当地的时区。
- (void)GetCurrentTimeStamp
{
NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
[objDateformat setDateFormat:@"yyyy-MM-dd"];
NSString *strUTCTime = [self GetUTCDateTimeFromLocalTime:@"2014-01-23"];
NSDate *objUTCDate = [objDateformat dateFromString:strUTCTime];
long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0);
NSLog(@"Local Time = %@---- UTC = %@ ----- TimeSatmp = %ld ---- TimeStamp = %lld",strTime,strUTCTime,unixTime,milliseconds);
}
- (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;
}