这是我的时间值,以毫秒为单位
UInt64 time = 1490237914000;
我使用以下方法来获取正确的时间表示
- (NSString *)commonRepresentationForTimerValue:(UInt64)timerValue
{
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timerValue];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitWeekday) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
NSInteger weekDay = [components weekday];
NSString *hourString;
if(hour < 10)
{
hourString = [NSString stringWithFormat:@"%@%li", @"0", (long)hour];
}
else
{
hourString = [@(hour) stringValue];
}
NSString *minuteString;
if(minute < 10)
{
minuteString = [NSString stringWithFormat:@"%@%li", @"0", (long)minute];
}
else
{
minuteString = [@(minute) stringValue];
}
NSString *weekDayString;
switch(weekDay)
{
case 1: weekDayString = @"Sunday"; break;
case 2: weekDayString = @"Monday"; break;
case 3: weekDayString = @"Tuesday"; break;
case 4: weekDayString = @"Wednesday"; break;
case 5: weekDayString = @"Thursday"; break;
case 6: weekDayString = @"Friday"; break;
case 7: weekDayString = @"Saturday"; break;
}
NSString *timerString = [NSString stringWithFormat:@"%@:%@ %@", hourString, minuteString, weekDayString];
return timerString;
}
这是我从上面的代码中得到的:
2017-03-23 12:20:02.318 AutoLayoutTest[21746:3371016] Time is 08:06 Tuesday
输出不正确(我知道这是不正确的)。
我用Java测试了相同的值
public static void main(String[] args)
{
Long timer = 1490237914000l;
final Calendar calendar = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("hh:mm");
calendar.setTimeInMillis(timer);
String weekDay = null;
switch (calendar.get(Calendar.DAY_OF_WEEK))
{
case 0: weekDay = "Sunday"; break;
case 1: weekDay = "Monday"; break;
case 2: weekDay = "Tuesday"; break;
case 3: weekDay = "Wednesday"; break;
case 4: weekDay = "Thursday"; break;
case 5: weekDay = "Friday"; break;
case 6: weekDay = "Saturday"; break;
}
System.out.println("Time is " + formatter.format(calendar.getTime()) + " " + weekDay);
}
我得到了正确的输出
Time is 10:58 Friday
我试图改变这行代码
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timerValue];
以下内容:
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:timerValue];
和
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:timerValue];
我的结果仍然不正确。
我不知道问题出在哪里,因为时间值是从纪元开始的时间,在java中它起作用。我必须有一些我在这里误解的东西,但我无法确定。
答案 0 :(得分:0)
NSDate * date = [NSDate dateWithTimeIntervalSince1970:timerValue / 1000];
并解决了这个问题。