1

i have the input string as 2012-07-27 and i want the output as date but with the same format like 2012-07-27

my code is

DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    try {
        Date today = df.parse("20-12-2005");
        System.out.println("Today = " + df.format(today));

                 } catch (ParseException e) {
        e.printStackTrace();
    }

my output is

Fri Jul 27 00:00:00 IST 2012

but i want to return the date object like like 2012-07-26 23:59:59 instead of a string any help please

any help is very thank full

user1642947
  • 69
  • 1
  • 5
  • 2
    Dates don't have format. – davidmontoyago Sep 06 '12 at 12:59
  • Use `format` method instead of `parse' – KV Prajapati Sep 06 '12 at 12:59
  • 4
    It sounds like you already *have* the string you want. You're trying to go from "2012-07-27" to "2012-07-27" - what am I missing here? – Jon Skeet Sep 06 '12 at 13:01
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Feb 16 '18 at 22:47

7 Answers7

7

You can use your same SimpleDateFormat you used to parse the date, to format the date into a string.

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = formatter.parse("2012-07-27");
System.out.println(date1); // prints Fri Jul 27 00:00:00 IST 2012
System.out.println(formatter.format(date1)); // prints 2012-07-26
FThompson
  • 28,352
  • 13
  • 60
  • 93
1

First, I think it's important to note that System.out.println implicitly invokes the toString method of its argument. The argument must be an Object or a subclass of it. And Date is a subclass of Object. That being said, take a look at the 1.7 Date#toString implementation,

public String toString() {
        // "EEE MMM dd HH:mm:ss zzz yyyy";
        BaseCalendar.Date date = normalize();
        StringBuilder sb = new StringBuilder(28);
        int index = date.getDayOfWeek();
        if (index == gcal.SUNDAY) {
            index = 8;
        }
        convertToAbbr(sb, wtb[index]).append(' ');                        // EEE
        convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' ');  // MMM
        CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd

        CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':');   // HH
        CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
        CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
        TimeZone zi = date.getZone();
        if (zi != null) {
            sb.append(zi.getDisplayName(date.isDaylightTime(), zi.SHORT, Locale.US)); // zzz
        } else {
            sb.append("GMT");
        }
        sb.append(' ').append(date.getYear());  // yyyy
        return sb.toString();
    }

The string representation of a Date object is specified as EEE MMM dd HH:mm:ss zzz yyyy. This is exactly what you're seeing.

If you want to display a Date object in a different format, use the SimpleDateFormat class. Its sole purpose is to add flexibility to the way a Date object is represented as a string.


Also...

One possible, albeit ridiculous workaround would be to create your own wrapper class,

public class MyDate{
    private final Date d;
    private final SimpleDateFormat sdf;

    public(Date d, SimpleDateFormat sdf){
        this.d = d;
        this.sdf = sdf;
    }

    // not recommended...should only be used for debugging purposes
    @Override
    public String toString(){
        return sdf.format(d);
    }
}
mre
  • 43,520
  • 33
  • 120
  • 170
0

You must use another SimpleDateFormat with the desired output format (format())

SJuan76
  • 24,532
  • 6
  • 47
  • 87
0

You can get a String representation for a date using the same SimpleDateFormat. The format method does this:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse("2012-07-27");
System.out.println(sdf.format(date1);
pb2q
  • 58,613
  • 19
  • 146
  • 147
0

There is no "format" property in java.util.Date. A Date instance is rather a simple object representing a moment in time (effectively, it's state is only defined by a unix timestamp it stores internally).

As others noted, use (for example) a SimpleDateFormat to print a Date instance as into a string.

david a.
  • 5,283
  • 22
  • 24
0
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse("2012-07-27");
System.out.println(dateFormat.format(date));
Reno
  • 33,594
  • 11
  • 89
  • 102
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72
0

tl;dr

LocalDate.parse( "2012-07-27" )
         .toString()

2012-07-27

Details

The modern way is with the java.time classes.

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

Standard format

Your input string format happens to comply with the ISO 8601 standard. The java.time classes use ISO 8601 formats by default when parsing/generating strings that represent date-time values. So no need to specify a formatting pattern at all.

LocalDate ld = LocalDate.parse( "2012-07-27" );

Do not conflate date-time objects with Strings representing their value. A date-time class/object can parse a string and generate a string, but the String is always a separate and distinct object.

String output = ld.toString();

2012-07-27

Custom format

If your input is non-standard, define a DateTimeFormatter to match.

String input = "20-12-2005" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
LocalDate ld = LocalDate.parse( input , f ) ;

ld.toString(): 2012-07-27

Table of date-time types in Java, both modern and legacy.


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