简体   繁体   English

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

[英]How to convert the following string to date or calendar object in Java?

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

You can use SimpleDateFormat#parse() to convert a String in a date format pattern to a Date . 您可以使用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

For an overview of all pattern characters, read the introductory text of SimpleDateFormat javadoc . 有关所有模式字符的概述,请阅读SimpleDateFormat javadoc的介绍性文本。


To convert it further to Calendar , just use Calendar#setTime() . 要将其进一步转换为Calendar ,只需使用Calendar#setTime()

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

I want to show "2017-01-11" to "Jan 11" and this is my solution. 我想将“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();
          }
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdf.parse(strDate);
Calendar cal = Calendar.getInstance();
cal.setTime(date);

try this.(strDate id your string format of Date) 试试这个。(strDate id你的字符串格式为Date)

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);    }   

 }
}      

Your given date is taken as a string that is converted into a date type by using the parse() method. 您的给定日期将被视为使用parse()方法转换为日期类型的字符串。 The parse() method invokes an object of DateFormat. parse()方法调用DateFormat的对象。 The setTime(Date date) sets the formatted date into Calendar. setTime(日期日期)将格式化日期设置为日历。 This method invokes to Calendar object with the Date object. 此方法使用Date对象调用Calendar对象。 refer 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM