This is my time value in milliseconds
UInt64 time = 1490237914000;
I use the following method to get the correct time representation
- (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;
}
This is what I am getting from the above code:
2017-03-23 12:20:02.318 AutoLayoutTest[21746:3371016] Time is 08:06 Tuesday
That output is incorrect (I know it's incorrect).
I tested the same value with 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);
}
I got the correct output
Time is 10:58 Friday
I tried to change this line of code
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timerValue];
to the following:
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:timerValue];
and
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:timerValue];
I still get incorrect result.
I don't know where the problem is, because the time value is the time from epoch, and in java it works. There must be something I am misunderstanding here but I am unable to determine it.
I solved the problem myself. I just divided the value of the timer by 1000.
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timerValue/1000];
and that solves the problem.