java字符串转换日期 月份位数,Java:将字符串日期转换为月份名称年份(MMM yyyy)...

I am new to Java. I am trying to convert date from string to MMM yyyy format (Mar 2016). I tried this

Calendar cal=Calendar.getInstance();

SimpleDateFormat month_date = new SimpleDateFormat("MMM yyyy");

String month_name = month_date.format(cal.getTime());

System.out.println("Month :: " + month_name); //Mar 2016

It is working fine. But when I use

String actualDate = "2016-03-20";

It is not working. Help me, how to solve this.

解决方案

Your format must match your input

for 2016-03-20

the format should be (just use a second SimpleDateFormat object)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

Full answer

SimpleDateFormat month_date = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

String actualDate = "2016-03-20";

Date date = sdf.parse(actualDate);

String month_name = month_date.format(date);

System.out.println("Month :" + month_name); //Mar 2016

Using java.time java-8

String actualDate = "2016-03-20";

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);

DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("MMM yyyy", Locale.ENGLISH);

LocalDate ld = LocalDate.parse(actualDate, dtf);

String month_name = dtf2.format(ld);

System.out.println(month_name); // Mar 2016

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值