gpt4 book ai didi

android - 将日历对象转换为日期 android 的问题

转载 作者:行者123 更新时间:2023-11-29 15:11:16 25 4
gpt4 key购买 nike

我想按如下方式将日历对象转换为日期。

int year,month,day;
mCalendarEnd = Calendar.getInstance();
year = mCalendarEnd.get(Calendar.YEAR);
month = mCalendarEnd.get(Calendar.MONTH)+1;
day = mCalendarEnd.get(Calendar.DAY_OF_MONTH);

现在将其转换为日期对象

Date d1 = new Date(day,month,year);

当我打印日期对象时:

System.out.println("Date : "+d1.getDay()+"/"+d1.getMonth()+"/"+d1.getYear());

它应该打印当前日期,但在上面的代码中它打印了错误的日期。知道如何解决这个问题吗?你所有的建议都是可观的。

最佳答案

你需要这样做

    //Set calendar
Calendar calendar = Calendar.getInstance();
Date date1 = calendar.getTime(); // gives a date object

//To get day difference, Just an example
calendar.add(Calendar.DAY_OF_MONTH, -7);
Date date2 = calendar.getTime(); // gives a date object

long differenceInMillis = Date1.getTime() - Date2.getTime();
long differenceInDays = TimeUnit.DAYS.convert(differenceInMillis, TimeUnit.MILLISECONDS);

或者不需要日期对象

    Calendar calendar = Calendar.getInstance();
long date1InMillis = calendar.getTimeInMillis();

calendar.add(Calendar.DAY_OF_MONTH, -7);
long date2InMillis = calendar.getTimeInMillis();

long differenceInMillis = date1InMillis - date2InMillis;
long differenceInDays = TimeUnit.DAYS.convert(differenceInMillis, TimeUnit.MILLISECONDS);
calendar.getTimeInMillis()

关于android - 将日历对象转换为日期 android 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31445634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com