Have a string like 2011-03-09T03:02:10.823Z, how to convert it to Date or calendar object in Java?
Asked
Active
Viewed 2.5k times
7
-
Possible duplicate of [How to convert a date String to a Date or Calendar object?](http://stackoverflow.com/questions/43802/how-to-convert-a-date-string-to-a-date-or-calendar-object) – Twonky Apr 12 '17 at 07:36
4 Answers
18
You can use SimpleDateFormat#parse()
to convert a String
in a date format pattern to a 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.
To convert it further to Calendar
, just use Calendar#setTime()
.
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
// ...

BalusC
- 1,082,665
- 372
- 3,610
- 3,555
-
what do you do if the pattern could be different? There are several different ways you can format a string that Date will recognize, right? What if you don't know which it will be? new Date(dateString) works as long as it's some valid format, but you don't have to specify it - is there an equivalent for this using Calendar? – Andrew Torr Oct 12 '17 at 17:54
2
I want to show "2017-01-11" to "Jan 11" and this is my solution.
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();
}

Community
- 1
- 1

Mabel Eain
- 159
- 6
1
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)

Ajay Mistry
- 951
- 1
- 14
- 30
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); }
}
}
Your given date is taken as a string that is converted into a date type by using the parse() method. The parse() method invokes an object of DateFormat. The setTime(Date date) sets the formatted date into Calendar. This method invokes to Calendar object with the Date object.refer

Akshatha
- 599
- 2
- 10
- 26