Time string to calendar java

Convert String to Calendar Object in Java

Note that this looses the timezone information. The Calendar object will have the system default TimeZone not the parsed one.

This should not be the top/accepted answer any more. Since Java 8 is already out for more than 4 years the answer should be updated to mention java.time . This Q/A comes up pretty prominent on google.

tl;dr

The modern approach uses the java.time classes.

YearMonth.from( ZonedDateTime.parse( "Mon Mar 14 16:02:37 GMT 2011" , DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" ) ) ).toString() 

Avoid legacy date-time classes

The modern way is with java.time classes. The old date-time classes such as Calendar have proven to be poorly-designed, confusing, and troublesome.

Define a custom formatter to match your string input.

String input = "Mon Mar 14 16:02:37 GMT 2011"; DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" ); 
ZonedDateTime zdt = ZonedDateTime.parse( input , f ); 

You are interested in the year and month. The java.time classes include YearMonth class for that purpose.

YearMonth ym = YearMonth.from( zdt ); 

You can interrogate for the year and month numbers if needed.

int year = ym.getYear(); int month = ym.getMonthValue(); 

But the toString method generates a string in standard ISO 8601 format.

String output = ym.toString(); 
String input = "Mon Mar 14 16:02:37 GMT 2011"; DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" ); ZonedDateTime zdt = ZonedDateTime.parse( input , f ); YearMonth ym = YearMonth.from( zdt ); int year = ym.getYear(); int month = ym.getMonthValue(); 
System.out.println( "input: " + input ); System.out.println( "zdt: " + zdt ); System.out.println( "ym: " + ym ); 

input: Mon Mar 14 16:02:37 GMT 2011

Live code

Conversion

If you must have a Calendar object, you can convert to a GregorianCalendar using new methods added to the old classes.

GregorianCalendar gc = GregorianCalendar.from( zdt ); 

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later — Part of the standard Java API with a bundled implementation.
    • Java 9 brought some minor features and fixes.
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Later versions of Android (26+) bundle implementations of the java.time classes.
    • For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
      • If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….

      Just to add to this, one can access the Day from the ZonedDateTime Object. For example: zdt.getDayOfMonth() (returns int ), zdt.getDayOfYear() (returns int ), or zdt.getDayOfWeek() (returns java.time.DayOfWeek ).

      Well, I think it would be a bad idea to replicate the code which is already present in classes like SimpleDateFormat .

      On the other hand, personally I’d suggest avoiding Calendar and Date entirely if you can, and using Joda Time instead, as a far better designed date and time API. For example, you need to be aware that SimpleDateFormat is not thread-safe, so you either need thread-locals, synchronization, or a new instance each time you use it. Joda parsers and formatters are thread-safe.

      Thanks for your input, I will certainly look into using Joda in the future, looks like it can be very useful

      @Jon Skeet Joda will not deserialize in Android. Joda is worth little unless you have no need to save dates and time.

      @FrankZappa: I’d disagree with that — you can do all your date/time calculations in Joda Time, but then convert to other types (maybe just strings for simplicity) for serialization purposes.

      Sorry, had to downvote, the answer is too old, it’s outdated to be the highest ranking answer. Today java.time is the way to go, Basil Bourque provided an excellent answer.

      @Scolytus: The top (and accepted) answer has 332 votes compared with 10 on this one. I think if you go round downvoting every 7+-year-old answer that has a better solution now, you’ll run out of downvotes. (I agree that Basil’s answer is good, and I’ve upvoted that.)

      No new Calendar needs to be created, SimpleDateFormat already uses a Calendar underneath.

      SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.EN_US); Date date = sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done Calendar cal = sdf.getCalendar(); 

      (I can’t comment yet, that’s why I created a new answer)

      Your solution looks elegant, but has two disadvantages: 1. The JavaDoc doesn’t guarantee that the behavior is, as expected. 2. At least for Java 6 you find a path at line 1353 where the calendar-object is cloned. So then then !date.equals(cal.getTime()).

      SimpleDateFormat is great, just note that HH is different from hh when working with hours. HH will return 24 hour based hours and hh will return 12 hour based hours.

      For example, the following will return 12 hour time:

      SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa"); 

      While this will return 24 hour time:

      SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); 

      Parse a time with timezone, Z in pattern is for time zone

      String aTime = "2017-10-25T11:39:00+09:00"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault()); try < Calendar cal = Calendar.getInstance(); cal.setTime(sdf.parse(aTime)); Log.i(TAG, "time https://i.stack.imgur.com/jjNOi.png" rel="noreferrer">enter image description here

      If we don't set the time zone in pattern like yyyy-MM-dd'T'HH:mm:ss. SimpleDateFormat will use the time zone which have set in Setting

)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
answered Oct 25, 2017 at 4:18
Add a comment |
3

Yes it would be bad practice to parse it yourself. Take a look at SimpleDateFormat, it will turn the String into a Date and you can set the Date into a Calendar instance.

)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
)">edited Mar 6, 2015 at 0:02
user3723884
3 2 bronze badges
answered Mar 14, 2011 at 16:12
Add a comment |
1

Simple method:

public Calendar stringToCalendar(String date, String pattern) throws ParseException

Источник

Convert String to Calendar Object in Java

converting String to Calendar. What is the easiest way?

DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(df.parse(stringInstanceRepresentingDate));

changing string to Calendar object value.

You should use a date format to parse your string

String dateStr = "2014-09-11";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
DateTime date = format.parse(dateStr);
Calendar cal = Calendar.getInstance();
cal.setTime(date);

How to convert a String to a Calendar object?

Change your data model to use a Date . This is the usual type to be stored in the database.

You can set the Date to a Calendar by using

Calendar c = Calendar.getInstance();
c.setTime(date);

To retrieve the Date from a Calendar you can use

Using a String to store a Date in a database needs formatting and parsing of the String s and also no comparision iside the database can be done.

How to convert a date String to a Date or Calendar object?

DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
try Date date = formatter.parse("01/29/02");
> catch (ParseException e) e.printStackTrace();
>

See SimpleDateFormat javadoc for more.

And to turn it into a Calendar , do:

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

I wanted to convert this string into calendar object of the specific date, but all it does is giving me the current date

I just ran this code and works fine for me. startDate.getTime() returns Tue Aug 01 15:18:01 PDT 2017 , which is as expected.
Only thing is you're missing a semicolon at the end of line startDateDate = dateFormat.parse(startDateStr) .

This might also help you: Set the Calendar to a specific date

how to convert the a string to a calendar object in java

Use Calendar cal = Calendar.getInstance() to get a calendar object with the current date and time. Using the add(), get(), and set() methods, you can set the calendar object correctly. For instance, to change the date to tomorrow's, you could do: cal.add(Calendar.DAY_OF_MONTH, 1);

To set the hour, cal.set(Calendar.HOUR, hr); where hr was initialized with the hour to be set. Similarly for minutes, etc.

How to place a date-time string into a Calendar object?

 String dateString=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse("2012-08-02 12:04:03"); 
Calender cal = Calender.getInstance();
cal.setTime(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(dateString).getTime());

wrap it around try catch though as the parse method would throw ParseException. and study the link provided by @user714965

Spring: Convert String from View to a Calendar Object

I'm assuming your Project class has the field DeadLineDate (fields should start with a lowercase character).

Annotate it with @DateTimeFormat like so

@DateTimeFormat(pattern = "yyyy/MM/dd") // or whatever pattern you want
private Calendar DeadLineDate;

Your client will then need to send the appropriate pattern.

Источник

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

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); // . 

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?

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

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

Источник

Читайте также:  Linking pdf files in html
Оцените статью