简体   繁体   中英

Set date format and then convert it in Date from String- Java

I am doing this to set a date format and then convert it into date datatype but it is not giving expected results.

 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
 DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
 String cur_date=dateFormat.format(new Date());
 myDb.setDOB(formatter.parse(cur_date));

Scenario is: I want current date to be converted in yyyy/mm/dd and then pass it in setDOB(Date date).

EDIT:Result added Result is Tue Jan 01 00:08:00 IST 2013

GUYS! I am not using 'mm',here I just mistakenly wrote mm in DateFormat it is also MM

EDIT AGAIN First I just used setDOB(new Date() ); but got formatting issue,

then I used SimpleDateFormat.format to set yyyy/MM/dd but it returns String so used

DateFormat.parse to convert it back into date type.

You're not using the same format. Case matters! "MM" is for months, "mm" is for minutes.

The issue is you MM in the format.

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
DateFormat formatter = new SimpleDateFormat("yyyy/mm/dd");
  • MM is month
  • mm is minute

Refer here for the detailed formats. So it should have been,

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");

+1 mael for spotting the format issue first, however...

Date is a container for the number of milliseconds since the epoch (Jan-1970-01-01 GMT), it does not care about the format of the values.

For example, the following...

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date now = new Date();
String cur_date = dateFormat.format(now);

try {
    System.out.println("Now = " + now);
    System.out.println("cur_date = " + cur_date);
    System.out.println("dateFormat.parse(cur_date) = " + dateFormat.parse(cur_date));
} catch (ParseException exp) {
    exp.printStackTrace();
}

Outputs...

Now = Thu Aug 01 18:08:39 EST 2013
cur_date = 2013/08/01
dateFormat.parse(cur_date) = Thu Aug 01 00:00:00 EST 2013

So you can lose important data about the date by doing this...

Leave formatting to when you want to display the value, not when you want to store it (if you can get away with it)

It sounds like you're expecting a Date to "know" its format. It doesn't. A Date object just contains a number of milliseconds since the Unix epoch. It doesn't know about time zones, or calendars, or string formats. It's just a date.

So your code should just be:

myDb.setDOB(new Date());

... and then handle the formatting of that wherever you're displaying it.

You re using different date String patterns. MM is for months, mm is for minutes (see SimpleDateFormat API )

Your setDOB is taking a Date object. I fail to see why you might want to format your date when giving it is as a parameter in your method call. Usually one formats a date when it needs to be rendered / stored somewhere.

formatter.parse is used to parse the String Date, It returns Date Object . The date is represented as a Date object or as the milliseconds as example since January 1, 1970, 00:00:00 GMT . I am not getting what actually your doing. Date object is always represented as in the above format.

The Question and other Answers all use troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

LocalDate

Apparently you want a date-only value.

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

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 .

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" );  // Or "Asia/Kolkata" , "Pacific/Auckland" , etc.
LocalDate today = LocalDate.now( z );

Generating strings

To generate a string representing the value of that LocalDate , simply call toString() . That method generates a string in standard ISO 8601 format.

String output = today.toString();

2017-01-23

Your desired format is close to that, using slash characters in place of hyphens. I suggest sticking with the standard formats whenever possible. But if you insist, just replace the characters.

String output = today.toString().replace( "-" , "/" );

For other formats use the DateTimeFormatter class. And be aware of that class' ability to automatically localize while generating a string.


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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM