3

I am finding the current time using Date date3 = Calendar.getInstance().getTime(); This gives me Thu Oct 25 11:42:22 IST 2012

Now I want my Date to be in the format 2012.10.25 and that too as a Date object and not a string.

I tried using the below code

DateFormat df = new SimpleDateFormat("yyyy.MM.dd");
Date startDate = df.parse(c_date1);

But when I finally use System.out.println(startDate.toString()); it again gives me Thu Oct 25 00:00:00 IST 2012. that is practically because the toString() function has been implemented in a way to show this format.

So is there any other way to get the date as 2012.10.25 and that too as the Date format. Date object is required because it is to be saved in db as a date field.

9
  • @BlueBullet. You guessed it from IST? That is for Indian Standard Time Commented Oct 25, 2012 at 6:23
  • lol... @RohitJain : IST means ISTanbul....:D Commented Oct 25, 2012 at 6:25
  • @RohitJain :D now is the op living in istanbul or india? Commented Oct 25, 2012 at 6:26
  • @BlueBullet. I guess India. Now thats only OP will decide, where he lives. We can't just transmit him anywhere. ;) Commented Oct 25, 2012 at 6:28
  • hehe... IST is for Indian Standard Time Commented Oct 25, 2012 at 6:29

8 Answers 8

11

you need to use df.format(Date) method to get date in required format

Sign up to request clarification or add additional context in comments.

6 Comments

The problem is the above function returns string .but i need the date asa Date object and not string
Do the formatting at the place you need to output the value (i.e. when you do System.out.println(...) )
but the above function returns string whereas i want date
just keep the date! format it only when you are doing the output. That is, don't do System.out.println(date.toString());, do System.out.println(df.format(date)); instead
Adrain i dont want to sys out the date. i want it to be saved in a variable so that i can use it later on.everybody here is interested in printing out
|
3
Date date3 = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd");
System.out.println(df.format(date3));

4 Comments

I think the question is not asked for this.
yes ...the question is not representing in the given format but saving it in the given format for further usage like saving in a dB
in DB, it is the same, unless you are storing it as varchar (which is not a good way), DB internally save the value as something else, without catering the formatting
The whole idea is the same! PostgreSQL is storing the value of Date, NOT the formatted string. You can do whatever formatting you want with that date value. I think you have to do some extra thinking to understand this story, as it is very basic and quite important. You will face lots of unnecessary problem in the future if you keep on thinking in your original way
3
    Date date3 = Calendar.getInstance().getTime();
    SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd");

    java.sql.Date date = null;

    try {
        date =new java.sql.Date(df.parse(df.format(date3)).getTime());
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(date);

Comments

3

tl;dr

Avoid terrible legacy date-time classes (Date, SimpleDateFormat). Use only the modern java.time classes.

LocalDate.now(                                    // Instantiate a date-only object, without time-of-day and without time zone.
    ZoneId.of( "India/Kolkata" )                  // Capture the current date, “today”, as seen by the people in a certain region (a time zone). For any given moment, the date varies around the globe by zone.
)
.format(                                          // Generate a String whose text represents the date-time value of our `LocalDate` object.
    DateTimeFormatter.ofPattern( "uuuu.MM.dd" )   // Specify your desired formatting pattern.
)

2012.10.25

To insert the date-only value for the current date into your database:

myPreparedStatement.setObject( 
    … , 
    LocalDate.now( ZoneId.of( "India/Kolkata" ) ) 
) ;

Confusing date-time value with a String

Date-time values do not have a “format”. Only strings have a format. Do not conflate the two. A date-time object can be instantiated by parsing a String. And a date-time object can generate a String to represent its value textually. But the date-time object and such strings remain separate and distinct.

it again gives me Thu Oct 25 00:00:00 IST 2012. that is practically because the toString() function has been implemented in a way to show this format.

No, the toString method does not “show” this format. That wording implies the format lives within the Date object. But the format does not live inside the Date object – the Date has no “format” at all. The toString method generates a String whose characters are arranged into this format.

Confusing date-only with date-time

You seem to interesting in a date-only values, without a time-of-day and without a time zone. If so, use the LocalDate class.

Create a LocalDate object for your desired value by parsing a string. Easiest to use the standard ISO 8601 format used by default in the java.time classes: YYYY-MM-DD.

String input = "2012-10-25" ;
LocalDate ld = LocalDate.parse( input ) ;  // No need to specify a formatting pattern, as ISO 8601 format used by default.

Your input string is in a non-standard format. Happens to be the same year-month-day order, so I would just replace the FULL STOP dots with hyphens.

String input = "2012.10.25".replace( "." , "-" ) ;  // Convert from custom format to standard ISO 8601 format.
LocalDate ld = LocalDate.parse( input ) ;  // No need to specify a formatting pattern, as ISO 8601 format used by default.

Or specify a formatting pattern.

String input = "2012.10.25" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu.MM.dd" ) ;
LocalDate ld = LocalDate.parse( input , f ) ;

Use that same formatter object to generate a string.

String output = ld.format( f ) ;  // Generate a string in this custom format.

Current date

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.

Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.

LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;

Database

As of JDBC 4.2 and later, we can directly exchange java.time objects with a database.

If storing this LocalDate object to a SQL-standard DATE column:

myPreparedStatment.setObject( … , ld ) ;

And retrieval:

LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;

If storing to a SQL-standard TIMESTAMP WITH TIME ZONE column, we need a date-time value rather than our date-only value. Perhaps you want to use the first moment of the day on that date? If so, let java.time determine that first moment. Do not assume 00:00. Anomalies such as Daylight Saving Time (DST) mean the day may start at another time such as 01:00.

ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;  // First moment of the day for that date for the people in India.

Most databases store zoned date-time moments by adjusting into UTC. Your JDBC driver and database may do that for you, or you can extract a UTC value (Instant) from your ZonedDateTime.

Instant instant = zdt.toInstant() ;  // Adjust from zoned time to UTC time.

myPreparedStatment.setObject( … , instant ) ;

And retrieval:

Instant instant = myResultSet.getObject( … , Instant.class ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

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.

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.

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.

Comments

1

Date object do not have any format. i.e. you can not convert any Date object into perticular format. Becuase it has its own to string format which will return when you print any date. You can convert any string format only.

You can convert or construct any Date Object from date string of the specific format. but that date object will not be in a specific format.

5 Comments

so date object will always represent a particular format in date object but it can be changed accordingly when we need to represent it as a string?
It can not be changed. For that you have to design custom class which extend the Date object and override the toString() method of Date class.
yes. i guess i have to override the tostring method to get the required format
yes...is there any other way by type conversion through which i could get the same result
Its not possible I suppose, still if you get any other solution please dont forget to tell me :)
1

Your question is just like asking:

I have an int variable of value 1234567, and I want it to store as "1,234,567" in that variable.

It is simply not reasonable.

How a value is stored, is nothing to do with how the value is presented.

1 Comment

I mean, an integer 1234567, we can format it as 1,234,567 or 1.234.567 or 1_234_567 or simply 1234567. All of them are just talking about the same value, which is 100101101011010000111 in memory. Date is the same, it is storing its value in some way. What you need to do is to format this value to some way you want when you need to output it.
1

If you want to save a date in db in given date format the you can use

DateFormat df = new SimpleDateFormat("yyyy.MM.dd");

    Date date3 = Calendar.getInstance().getTime();

    String startDate = df.format(date3);

    try {

    java.sql.Date date = new java.sql.Date(df.parse(startDate).getTime());

    System.out.println(date);

    } catch (ParseException ex) {
      Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }

1 Comment

this date which u r printing will give a timestamp also along with the date
-1

It's very simple

SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
format.parse(dateObject.toString());

1 Comment

FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9. See Tutorial by Oracle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.