java 设置日历日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16246193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:22:33  来源:igfitidea点击:

Set date of calendar

javacalendar

提问by ubundude

Ok, so what I'm trying to do is to set the set the date of a calendar instance, and then return the week_of_year. I am doing so by using the Calendar.set() functio

好的,所以我要做的是设置日历实例的日期,然后返回 week_of_year。我这样做是通过使用 Calendar.set() 函数

public String weekInYearForm = "ww";
SimpleDateFormat formWIM = new SimpleDateFormat(weekInYearForm, Locale.US);

Calendar lc = Calendar.getInstance();
    lc.set(Calendar.YEAR, lYear);
    lc.set(Calendar.MONTH, lMonth);
    lc.set(Calendar.DAY_OF_MONTH, lDay);


    wiy = formWIM.format(lc.get(Calendar.WEEK_OF_YEAR));

To get the lYear, lMonth, and lDay values, I am passing a string in the format 04/26/2013to through the following steps:

要获取 lYear、lMonth 和 lDay 值,我将04/26/2013通过以下步骤传递格式为 to的字符串:

String[] arrDate = dateIn.split("/");
int lMonth = Integer.parseInt(arrDate[0]) - 1;
Log.d("SaveHandler", "Month is: " + lMonth);
int lDay = Integer.parseInt(arrDate[1]);
Log.d("SaveHandler", "Day is: " + lDay);
int lYear = Integer.parseInt(arrDate[2]);
Log.d("SaveHandler", "Year is: " + lYear);

The problem I am facing is that when I look at what is outputed to wiy, it is always 1. Upon some further debugging, I realized that the time is being left at epoch time, and not setting to the values I need.

我面临的问题是,当我查看输出到 wiy 的内容时,它始终为 1。经过进一步调试,我意识到时间被保留在纪元时间,而不是设置为我需要的值。

I also tried using lc.set(lYear, lMonth, lDay), also to no avail. If anyone has any ideas, I would greatly appreciate them.

我也试过使用lc.set(lYear, lMonth, lDay),也无济于事。如果有人有任何想法,我将不胜感激。

*EDIT: I did some debugging earlier and it is returning 1970 for the year and 0 for the month.

*编辑:我早些时候做了一些调试,它返回 1970 年和 0 月。

回答by Ilya

use

利用

formWIM.format(lc.getTime());

instead of

代替

formWIM.format(lc.get(Calendar.WEEK_OF_YEAR));  

EDIT
You can parse your date (instead of dateIn.split(etc.)

编辑
您可以解析您的日期(而不是dateIn.split(等)

  SimpleDateFormat monthDayYear = new SimpleDateFormat("MM/dd/yyyy", Locale.US); //04/26/2013
  Date date = monthDayYear.parse("04/26/2013");  

and then format it

然后格式化

 SimpleDateFormat formWIM = new SimpleDateFormat("ww", Locale.US);  
 formWIM.format(date);

回答by cahen

This code is correct, the problem is in formWIM.format(...)or the battery of your motherboard clock is drained.

此代码是正确的,问题出在formWIM.format(...)或主板时钟的电池电量耗尽。