-1

I wan't to convert a string Calendar Object (calendar.toString()) to calendar object. I tried this solution but it show in console the date of the day '12-05-2017' not '02-02-2017'

String calendar object format:

java.util.GregorianCalendar[time=1485993600000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Africa/Casablanca",offset=0,dstSavings=3600000,useDaylight=true,transitions=102,lastRule=java.util.SimpleTimeZone[id=Africa/Casablanca,offset=0,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=10800000,endTimeMode=0]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2017,MONTH=1,WEEK_OF_YEAR=5,WEEK_OF_MONTH=1,DAY_OF_MONTH=2,DAY_OF_YEAR=33,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]

             Calendar calendar = GregorianCalendar.getInstance();
             calendar.setTime(new Date("2017/02/02"));
             System.out.println("calendar : "+calendar.getTime());
             try {
                 GregorianCalendar gc = new GregorianCalendar();
                 DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
                 System.out.println("calendar : "+calendar.getTime());
                 gc.setTimeZone(TimeZone.getTimeZone(calendar.toString()));
                 System.out.println("tme zone : "+gc.getTimeZone());
                 System.out.println("calendar : "+calendar.getTime());
                 System.out.println("calendar : "+calendar.toString());
                 System.out.println(formatter.format(gc.getTime()));
             }
             catch(Exception e) {
                 //If exception, return server TimeStamp
             }

Any help please

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
imane
  • 21
  • 1
  • 4
  • 1
    Tried what solution? You haven't posted any code. – azurefrog May 11 '17 at 23:23
  • 1
    Ah, no. I'd consider storing the time (long) and timezone information, maybe formatting into a `String`, but I'd not consider trying to parse the `toString` value from `Calendar` ... I'd also suggest having a look at the new Java Time API, as it supports and number of ISO formats out of the box – MadProgrammer May 11 '17 at 23:24
  • @azurefrog I added the code to my post – imane May 11 '17 at 23:41
  • First trouble is `Calendar` is an abstract class, `GregorianCalendar` being the most widely used subclass. If you only know you have a `Calendar` object, you may have an instance of a different subclass with a completely different `toString` method. You are calling `GregorianCalendar.getInstance()`, but this is a call to `Calendar.getInstance()` and doesn’t guarantee a `GregorianCalendar` instance. – Ole V.V. May 12 '17 at 10:31
  • I know this is an oversimplified answer: Use `java.time.LocalDate` instead of `GreforianCalendar`. `LocalDate.parse()` will readily parse the string from `LocalDate.toString()`. – Ole V.V. May 12 '17 at 10:45
  • My feeling it can be done with `GregorianCalendar`, or at least you can come close, but it will take much parsing work. – Ole V.V. May 12 '17 at 11:06
  • Why do you want to do this at all? – Ole V.V. May 12 '17 at 13:41

4 Answers4

1

If that were me, I’d look at all the setters of both Calendar and GregorianCalendar and see if I thought I could extract the values needed for the setters from the string. “time=1485993600000” should give you the most important information, the time, and you can feed it into setTimeInMillis(). You ought to be able to get a time zone out of “Africa/Casablanca”. And so forth. You can probably use regular expressions for extracting the fields from the string.

You’d probably have to live with not covering all cases. Your particular GregorianCalendar seems to contain a sun.util.calendar.ZoneInfo and a java.util.SimpleTimeZone; I don’t know whether that is always the case nor what other possibilities there are.

The strict test of your attempt is easy: just call toString() again on your newly constructed instance and see if you get the same string. The difficulty comes if you accept some differences and you need to determine whether the actual differences lie within what you have decided to accept.

Or really, I wouldn’t want to bother if I could avoid it. I’d see if I could find an easier task or an easier way to obtain what you are really trying to obtain. As I already said in a comment, one may use java.time.LocalDate instead of GregorianCalendar. LocalDate.parse() will readily parse the string from LocalDate.toString(), and the problem is solved. Just to give one example of another way to look at it.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
1

In your code, you have two separate GregorianCalendar objects - one called calendar and one called gc. You're setting one calendar object to the date that you want, then printing out the other one.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
  • 1
    Sorry, @OleV.V. I guess I overreacted. I still believe the crux of the matter is that he assigned a value to `calendar` then printed `gc`, expecting his value to magically have transferred from one object to the other - which is an issue that your answer never addressed. Your answer does, however, contain some excellent other information, and it was clearly useful in leading OP to the correct answer. My apologies again for my earlier comment. – Dawood ibn Kareem May 13 '17 at 20:11
  • No hard feelings. – Ole V.V. May 13 '17 at 20:14
1

Thanks @Ole , I finally found the solution and it works.

             Calendar calendar = Calendar.getInstance();;
             calendar.setTime(new Date("2017/02/02"));
             String[] ds = calendar.toString().split("=");
             String[] ds2 = ds[1].split(",");
             try {
                 Calendar cal = Calendar.getInstance();;
                 DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
                 cal.setTimeInMillis(Long.valueOf(ds2[0]));
                 System.out.println(formatter.format(cal.getTime()));
             }
             catch(Exception e) {

             }
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
imane
  • 21
  • 1
  • 4
0

java.time

You are using terrible old classes that are now supplanted by the much superior java.time classes.

Instantiate a LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate ld = LocalDate.parse( "2017-02-02" ) ;

To generate a string in standard ISO 8601 format, call toString.

String output = ld.toString() ;

2017-02-02

For other formats use the DateTimeFormatter class.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
String output = ld.format( f ) ;

02-02-2017

Your Question is not clear. If the problem is that your code is being handed a GregorianCalendar object, convert it to java.time.ZonedDateTime. Call new conversion methods added to the old classes.

if( myCalendar instanceOf GregorianCalendar ) {
    ZonedDateTime zdt = myCalendar.toZonedDateTime() ;
}

Extract the date-only value you desire, as a LocalDate.

LocalDate ld = zdt.toLocalDate() ;

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.

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

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

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154