如何在Java中将以下字符串转换为日期或日历对象?

时间:2011-03-15 02:18:29

标签: java android

有一个像2011-03-09T03:02:10.823Z的字符串,如何在Java中将它转换为日期或日历对象?

4 个答案:

答案 0 :(得分:17)

您可以使用SimpleDateFormat#parse()将日期格式模式中的String转换为Date

String string = "2011-03-09T03:02:10.823Z";
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
Date date = new SimpleDateFormat(pattern).parse(string);
System.out.println(date); // Wed Mar 09 03:02:10 BOT 2011

有关所有模式字符的概述,请阅读SimpleDateFormat javadoc的介绍性文本。


要将其进一步转换为Calendar,只需使用Calendar#setTime()

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
// ...

答案 1 :(得分:2)

我想展示" 2017-01-11"至" 1月11日"这是我的解决方案。

   SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
   SimpleDateFormat df_output = new SimpleDateFormat("MMM DD");
   Calendar cal=Calendar.getInstance();

   Date date = null;
        try {
              date = df.parse(selectedDate);
              String outputDate = df.format(date);
              date = df_output.parse(outputDate);


              cal.setTime(date);

          } catch (ParseException e) {
            e.printStackTrace();
          }

答案 2 :(得分:1)

import java.util.*;
import java.text.*;
public class StringToCalender {
public static void main(String[] args) {
try {    String str_date="11-June-07";
     DateFormat formatter ; 
 Date date ; 
      formatter = new SimpleDateFormat("dd-MMM-yy");
          date = (Date)formatter.parse(str_date); 
   Calendar cal=Calendar.getInstance();
   cal.setTime(date);
           System.out.println("Today is " +date );
} catch (ParseException e)
{System.out.println("Exception :"+e);    }   

 }
}      

您的给定日期将被视为使用parse()方法转换为日期类型的字符串。 parse()方法调用DateFormat的对象。 setTime(日期日期)将格式化日期设置为日历。此方法使用Date对象调用Calendar对象。refer

答案 3 :(得分:1)

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdf.parse(strDate);
Calendar cal = Calendar.getInstance();
cal.setTime(date);

试试这个。(strDate id你的字符串格式为Date)