How to initialize Gregorian calendar with date as YYYY-MM-DD format?

10,626

Solution 1

First, you may hate me for reiterating, you need to understand that there’s a difference between a date and a string representation of that date; a difference between the fundamental data and a string representation of it.

Second, you can use LocalDate (and the other Java date and time classes) with Java 7 if you want. It is (and they are all) in the ThreeTen-Backport , a back-port of the Java SE 8 date-time classes to Java SE 6 and 7.

Since I gather that LocalDate fits your requirements much better, I really think you should give it a thought or two. So instead of your cal I suggest

private LocalDate date = LocalDate.now(ZoneId.systemDefault());

Also think about whether you want the current time zone setting of your JVM (as the above will give you) or you want to control which time zone you use. It will make a difference.

Finally, if you really insist. As you have understood by now, I cannot give you a string in a GregorianCalendar. You may discard the time part of your GregorianCalendar so you only have the date part. And you may format it into a string of your liking.

public class GregorianCalendarDemo {

    private GregorianCalendar cal;

    public GregorianCalendarDemo() {
        cal = new GregorianCalendar(TimeZone.getDefault(), Locale.getDefault());
        // discard time of day so we only have the date
        cal.set(Calendar.HOUR_OF_DAY, cal.getActualMinimum(Calendar.HOUR_OF_DAY));
        cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE));
        cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND));
        cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND));
    }

    protected GregorianCalendar getCal() {
        return cal;
    }

    public String getFormattedCal() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(getCal().getTime());
    }
}

When I just called getFormattedCal(), it returned 2017-05-25.

Again, decide whether default values for time zone and locale are fine or you want something else.

You might have thought that we could discard the hours with just cal.set(Calendar.HOUR_OF_DAY, 0):, and similarly with minutes and seconds. It would work in 99 % of all cases at least. However, with transistion to summer time (daylight savings time), the day is not guaranteed to begin at 0 hours, so the above code is more bulletproof.

Link

ThreeTen Backport home

Solution 2

You can try to use SimpleDateFormat for example :

GregorianCalendar cal = new GregorianCalendar();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
format.setCalendar(cal);
String result = format.format(cal.getTime());
System.out.println(result);//today is 2017-05-25

To convert String to GregorianCalendar :

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssX");
Date date = format.parse("2017-05-25T14:36:52+03:00");
GregorianCalendar cal2 = new GregorianCalendar();
cal2.setTime(date);
Share:
10,626

Related videos on Youtube

Sachin Chaudhari
Author by

Sachin Chaudhari

Updated on June 04, 2022

Comments

  • Sachin Chaudhari
    Sachin Chaudhari almost 2 years

    I have a class which contains a variable

    private GregorianCalendar cal;
    

    Now I want to initialize it with a date in yyyy-mm-dd format, I tried using the default constructor but the output I get is something like this "2017-05-25T14:36:52+03:00", I only want "2017-05-25" date part?

    How do I achieve it?

    • assylias
      assylias almost 7 years
      If you have the choice, don't use GregorianCalendar but java time (in Java 8+) or Joda., which have proper "LocalDate" classes.
    • Francesco Pitzalis
      Francesco Pitzalis almost 7 years
      You need to format the date. Check SimpleDateFormat. If you want some specific help with your code you should write your attempt in your question.
    • Jon Skeet
      Jon Skeet almost 7 years
      "Now I want to initialize it with a date in yyyy-mm-dd format" - a date doesn't have a format in either java.util.Date or java.util.Calendar. Apply formatting at the point where you convert the value to a string.
    • Sachin Chaudhari
      Sachin Chaudhari almost 7 years
      I tried using the SimpleDateFormat but it returns string, how do i store a string in variable whose data type is GregorianCalendar?
    • Sachin Chaudhari
      Sachin Chaudhari almost 7 years
      The final output should be in cal variable
    • Ole V.V.
      Ole V.V. almost 7 years
      I sounds like you’ve misunderstood. Try to keep two concepts apart: the value of a variable and the presentation of the same variable. Just as an int that holds a 7 can be printed as 7 or 07, 007 or +7, your GregorianCalendar can be printed as 2017-05-25T14:36:52+03:00 or just 2017-05-25. In both cases, that variable holds the same value.
    • Ole V.V.
      Ole V.V. almost 7 years
      And just as there is no such thing as storing a string into an int variable in Java, there is also no such think as storing a string in a GregorianCalendar.
    • Ole V.V.
      Ole V.V. almost 7 years
      It seems to me that what you are really asking for, is a LocalDate to use instead of your GregorianCalendar. Its default format is 2017-05-25 (just as integers and GregorianCalendar at may be formatted into other formats if desired).
    • Jon Skeet
      Jon Skeet almost 7 years
      @OleV.V.: LocalDate would be better in terms of an API, but that doesn't have a format either, and the OP really needs to understand that there's a difference between the fundamental data and a string representation of that.
    • Sachin Chaudhari
      Sachin Chaudhari almost 7 years
      Yes I understand that, but I need to pass only LocaleDate and I am using GregorianCalendar, and I am using JAVA 7 so i cannot use java time
    • Basil Bourque
      Basil Bourque almost 7 years
      @SachinChaudhari Much of the java.time functionality is back-ported to Java 6 and Java 7 in the ThreeTen-Backport project. Avoid the troublesome old legacy date-time classes; they are a wretched mess.
  • Sachin Chaudhari
    Sachin Chaudhari almost 7 years
    I tried using the SimpleDateFormat but it returns string, how do i store a string in variable whose data type is GregorianCalendar?
  • Sachin Chaudhari
    Sachin Chaudhari almost 7 years
    I dont want to print the data, i want to send it in a XML tag but i need to send the date in yyyy-mm-dd format .
  • Youcef Laidani
    Youcef Laidani almost 7 years
    then send a String instead of GregorianCalendar