开发者

What is the Android equivalent of iPhone's NSCalendar?

What might be the Android equivalent of the following iPhone code?

NSCalendar *calender = [[[NSCalendar alloc] initWithCalendarIdent开发者_如何学Goifier:NSGregorianCalendar] autorelease];
int units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *components = [calender components:units fromDate:[NSDate date] toDate:destinationDate options:0];

I am trying to do a date countdown to show the number of years, months, days, hours, minutes and seconds in a consecutive manner, not show the years, months, days, hours, minutes and seconds as a whole.

I have this, but I cannot get the hours, minutes and seconds. When I play with the hours, I keep getting hours in the days, not hours left.

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(myDate);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        long nat = Math.round(date.getTime() / 1000);
        long totaldifference = Math.abs(d1-d2);

        long date_diff = Math.round(totaldifference/(24*3600));
        //year
        double year2 = Math.floor(date_diff/365);
        date_diff-=year2*365;

        double month2 = Math.floor(date_diff/30.5);
        date_diff-=month2*30.5;

        long day2 = date_diff;


To get a Calendar, you can do this:

Calendar cal = Calendar.getInstance()

Doing it this way will initialize it to the current date and time. Check the documentation if you need to set it to a different date or time.

To get the year, month, day, and so on, you can do this:

int year = cal.get(Calendar.YEAR)
int month = cal.get(Calendar.MONTH)
int day = cal.get(Calendar.DATE)

To "count down" on that, you can add a negative of whatever unit you want to count down in:

cal.add(Calendar.SECOND, -1)


Have a look at the documentation for calendar it should help. You get the year, month, day etc all seperately so should be easy to implement your countdown. Its a base class so you should be able to extend it to do what you need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜