Question

I want to create a DateTime String with format like 2013-08-30T15:06:00 using three strings.One String has Date "30-aug-2013" and second string has time "15:06" and last string has days value "2".Now I want to use these three Strings to create a Resulted string like "2013-08-28T15:06:00". The days value is to create date in past, so in this case the date changes from 30th aug to 28 aug

Solution I have tried:

public String getFormattedDate(String date, String selectedDays, String time) {
    String dtStart = date;  
    SimpleDateFormat  format = new SimpleDateFormat("dd-MM-yyyy");  
    try {  
        Date dateObject = format.parse(dtStart);  
        System.out.println(date);  
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(dateObject);
        calendar.add(Calendar.DAY_OF_MONTH, Integer.valueOf(selectedDays));
        System.out.println(calendar.getTime()); 
    } catch (ParseException e) {  
        // TODO Auto-generated catch block  
        e.printStackTrace();  
    }
}

In above solution calendar.add will add the days instead of removing days from date.Also I don't know how to use the time string to set it on the date Object.

Was it helpful?

Solution

If your time String is always in that format, you'll need to use time.split(":") to get the hours and minutes.

You might want to specify the output format instead of using the Locale default format also.

Add a minus sign to substract instead of adding for the Calendar.add().

Your code use dd-MM-yyyy but your month part is written, 08-aug-2013 which should be parsed using dd-MMM-yyyy instead.

This should output as you specified

  public static String getFormattedDate(String date, String selectedDays, String time) {
    String dtStart = date;
    Calendar calendar = new GregorianCalendar();
    calendar.clear();
    SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy"); // This should be MMM and not MM according to the date format 08-aug-2013
    try {
      Date dateObject = format.parse(dtStart);
      System.out.println(date);
      calendar.setTime(dateObject);
      String[] hoursMins = time.split(":");
      int hours = Integer.valueOf(hoursMins[0]);
      int minutes = Integer.valueOf(hoursMins[1]);
      calendar.set(Calendar.HOUR_OF_DAY, hours);
      calendar.set(Calendar.MINUTE, minutes);
      calendar.set(Calendar.SECOND, 0); // Here, I have no idea where you get the seconds, so I just set them to 0
      calendar.add(Calendar.DAY_OF_MONTH, -Integer.valueOf(selectedDays)); // Add a minus sign to substract
      // System.out.println(calendar.getTime());
      // Use a SimpleDateFormat instead

      System.out.println(outputFormat.format(calendar.getTime()));
      // System.out.println(calendar.getTime());
    } catch (ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return outputFormat.format(calendar.getTime());
  }

For a good place to read about formatting symbols, check the bottom of this link, it's pretty well explained.

Calling getFormattedDate("08-aug-2013", "2", "15:05"); with this code output 2013-08-06T15:05.

Edit : I forgot the seconds, the output is now : 2013-08-06T15:05:00

OTHER TIPS

Avoid j.u.Date & .Calendar

The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Instead use the Joda-Time library.

Time Zone

The other answers ignore the critical issue of time zone. You must specify whether this string represents a date-time in Paris, Tukwila, or Kolkata. If you do not specify, the JVM's default time zone is applies.

Language

The other answers fail to specify the language by which to parse the name-of-month.

Example Using Joda-Time

String input = "30-aug-2013" + "15:06";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "d-MM-yyyyH:mm" );
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
java.util.Locale locale = java.util.Locale.ENGLISH;
DateTime dateTime = formatter.withLocale( locale ).withZone( timeZone ).parseDateTime( input" );

If required, convert to a java.util.Date, automatically adjusting to UTC as a Date has no time zone.

java.util.Date date = dateTime.toDate();

Calendar.add can remove days by adding a negative value:

SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy");  <-- check your format      
Date d = format.parse("08-aug-2013");

Calendar c = new GregorianCalendar();
c.setTime(d);
c.add(Calendar.DAY_OF_MONTH, -2);  <-- see that you are parsing to a negative int
System.out.println(c.getTime());

Prints:

Tue Aug 06 00:00:00 EDT 2013

final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);

String date = mYear + "-" + mMonth + "-" + mDay; // + time + ... so on
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top