2

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.

Nishant
  • 54,584
  • 13
  • 112
  • 127
saurabh j
  • 89
  • 1
  • 1
  • 7
  • @BlueBullet. You guessed it from `IST`? That is for `Indian Standard Time` – Rohit Jain Oct 25 '12 at 06:23
  • lol... @RohitJain : IST means ISTanbul....:D – Nandkumar Tekale Oct 25 '12 at 06:25
  • @RohitJain :D now is the op living in istanbul or india? – Juvanis Oct 25 '12 at 06:26
  • @BlueBullet. I guess India. Now thats only OP will decide, where he lives. We can't just transmit him anywhere. ;) – Rohit Jain Oct 25 '12 at 06:28
  • hehe... IST is for Indian Standard Time – saurabh j Oct 25 '12 at 06:29
  • 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. – Bhavik Ambani Oct 25 '12 at 06:35
  • who the heck has downgraded this question. nobody seems to have an answer..bloody hell – saurabh j Oct 25 '12 at 07:57
  • 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 Mar 20 '18 at 06:45
  • @saurabhj `IST` is for *India Standard Time*, *Ireland Standard Time*, and others. These 3-4 letter abbreviations are **not true time zones**, are not standardized, and are not even unique! Use [proper time zone names](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) in format of `continent/region` such as `India/Kolkata` or `Europe/Dublin`. – Basil Bourque Mar 20 '18 at 07:09

8 Answers8

10

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

Nishant
  • 54,584
  • 13
  • 112
  • 127
NIKUNJ SANGHADIA
  • 342
  • 4
  • 15
  • 2
    The problem is the above function returns string .but i need the date asa Date object and not string – saurabh j Oct 25 '12 at 06:31
  • Do the formatting at the place you need to output the value (i.e. when you do System.out.println(...) ) – Adrian Shum Oct 25 '12 at 06:41
  • 1
    but the above function returns string whereas i want date – saurabh j Oct 25 '12 at 06:47
  • 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 – Adrian Shum Oct 25 '12 at 07:04
  • 2
    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 – saurabh j Oct 25 '12 at 07:54
  • Then you shouldn't even care about the format. People using that date value should do their work to interpret or format it – Adrian Shum Oct 25 '12 at 07:58
3
Date date3 = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd");
System.out.println(df.format(date3));
Erwin
  • 4,757
  • 3
  • 31
  • 41
NIKUNJ SANGHADIA
  • 342
  • 4
  • 15
  • 1
    I think the question is not asked for this. – Bhavik Ambani Oct 25 '12 at 06:50
  • 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 – saurabh j Oct 25 '12 at 06:52
  • 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 – Adrian Shum Oct 25 '12 at 07:07
  • 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 – Adrian Shum Oct 25 '12 at 08:03
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);
NIKUNJ SANGHADIA
  • 342
  • 4
  • 15
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.

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

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);
    }
Pratap
  • 591
  • 8
  • 25
Rajshri
  • 4,163
  • 2
  • 15
  • 17
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.

Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86
  • 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? – saurabh j Oct 25 '12 at 06:38
  • 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. – Bhavik Ambani Oct 25 '12 at 06:43
  • yes. i guess i have to override the tostring method to get the required format – saurabh j Oct 25 '12 at 06:45
  • yes...is there any other way by type conversion through which i could get the same result – saurabh j Oct 25 '12 at 06:58
  • 1
    Its not possible I suppose, still if you get any other solution please dont forget to tell me :) – Bhavik Ambani Oct 25 '12 at 07:01
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.

Adrian Shum
  • 38,812
  • 10
  • 83
  • 131
  • 2
    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. – Adrian Shum Oct 25 '12 at 07:02
-1

It's very simple

SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
format.parse(dateObject.toString());
  • 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 Mar 20 '18 at 06:45