
那要看对方提供的是什么对象,如果是String类型的,那么就需要先转成Date对象,再转成Calendar对象,如果直接给的Date那么更简单,转成Calendar就可以了。
import javatextSimpleDateFormat;
import javautilCalendar;
import javautilDate;
public class Test12{
public static void main(String args[]) throws Exception{
String d1 = "2012-04-02";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdfparse(d1);
Calendar c = CalendargetInstance();
csetTime(date);
Systemoutprintln(cget(CalendarMONTH));
}
}
这个月份是从0开始到11的,所以4月会输出3
Calendar cal = CalendargetInstance();
calsetTime(new Date());
int month = calget(CalendarMONTH); //注意月份是从0开始的,比如当前7月,获得的month为6
现在Date下面的大部分方法已经废弃,不推荐使用。
String str = new javatextSimpleDateFormat("yyyy-mm-")format(new javautilDate())+"04";
可以通过日期的add(CalendarMONTH, 1)方法进行月份切换,输出每个满足条件的值
Date d1 = new SimpleDateFormat("yyyy-MM")parse("2015-6");//定义起始日期
Date d2 = new SimpleDateFormat("yyyy-MM")parse("2016-5");//定义结束日期
Calendar dd = CalendargetInstance();//定义日期实例
ddsetTime(d1);//设置日期起始时间
while(ddgetTime()before(d2)){//判断是否到结束日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
String str = sdfformat(ddgetTime());
Systemoutprintln(str);//输出日期结果
ddadd(CalendarMONTH, 1);//进行当前日期月份加1
}
结果:
import javatextSimpleDateFormat;
import javautilCalendar;
import javautilDate;
public class Main {
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
public static void main(String args[]) {
Date d = new Date();
// 月初
Systemoutprintln("月初" + sdfformat(getMonthStart(d)));
// 月末
Systemoutprintln("月末" + sdfformat(getMonthEnd(d)));
Date date = getMonthStart(d);
Date monthEnd = getMonthEnd(d);
while (!dateafter(monthEnd)) {
Systemoutprintln(sdfformat(date));
date = getNext(date);
}
}
private static Date getMonthStart(Date date) {
Calendar calendar = CalendargetInstance();
calendarsetTime(date);
int index = calendarget(CalendarDAY_OF_MONTH);
calendaradd(CalendarDATE, (1 - index));
return calendargetTime();
}
private static Date getMonthEnd(Date date) {
Calendar calendar = CalendargetInstance();
calendarsetTime(date);
calendaradd(CalendarMONTH, 1);
int index = calendarget(CalendarDAY_OF_MONTH);
calendaradd(CalendarDATE, (-index));
return calendargetTime();
}
private static Date getNext(Date date) {
Calendar calendar = CalendargetInstance();
calendarsetTime(date);
calendaradd(CalendarDATE, 1);
return calendargetTime();
}
}
这是一个月的 你改改就能写出上个月的了吧
以上就是关于java 如何解析年月日,比如别人给我传一个年月日,我想单独获取月份怎么解析谢谢高手!全部的内容,包括:java 如何解析年月日,比如别人给我传一个年月日,我想单独获取月份怎么解析谢谢高手!、JAVA语句怎么把日期(类型为DATA)中的月份提取出来、java 获取每个月的固定时间等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)