简体   繁体   中英

converting a string date into US format in java

I have the below code in which date come as string type and I have to set it in US format so below I have shown it

private static final SimpleDateFormat usOutputDate =  new SimpleDateFormat("MM/dd/yyyy");

and inside a method I have written the below code and inside dealDateString the value is coming as 02-Mar-2015

// dealDateString = 02-Mar-2015 
java.util.Date  dealDate = extractDate(dealDateString); 
//here its value get converted in US format that is 03/02/2015
String dd = usOutputDate.format(dealDate); 

DateFormat format = new SimpleDateFormat("MM/dd/yyyy", Locale.US); 
// ***issue comes here as it get back converted in US format ***
java.util.Date date =  format.parse(dd);
brokerInvoiceLineItem.setDealDate(new Date(date));

as shown in the above code that's it value inside String dd is 03/02/2015 but the issue comes at format variable where its value get converted back in UK format which i do not want please advise how can i convert it in UK format as it is already converted in US format previously stored inside String dd .

The accepted Answer by Silambarasan Poonguti and other Answer by Ramesh Ponnada are both correct. But both are outdated, using the old date-time classes bundled with the earliest versions of Java. Those classes have proven to be troublesome, confusing, and flawed.

java.time

The java.time framework built into Java 8 and later supplants the old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310 . Extended by the ThreeTen-Extra project. See the Oracle Tutorial .

LocalDate

These new classes include LocalDate for handling a date-only value without time-of-day nor time zone. Though a LocalDate does not contain a time zone, be aware that a time zone is crucial in determining a date such as 'today'. The date is not the same around the world at any one moment, as a new day dawns earlier in the east.

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

Parsing A String

To parse a string, specify a coded pattern. This pattern is similar to that used in the old java.text.SimpleTextFormat but not exactly the same. So be sure to study the java.time.format.DateTimeFormatter doc closely.

Note that we use a triple M to specify that we expect an abbreviation of the name of the day. This is the key to solving the problem in the Question.

Also note that we specify a Locale, which tells java.time the human language we expect for that abbreviated name of day.

String input = "02-Mar-2015";
Locale locale = Locale.US;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "dd-MMM-yyyy" ).withLocale ( locale );
LocalDate localDate = LocalDate.parse ( input , formatter );

Dump to console. By default the toString methods in java.time use standard ISO 8601 formats.

System.out.println ( "localDate: " + localDate );

localDate: 2015-03-02

Generating A String

When generating a String representation of a date-time value, usually best to let java.time localize it for you rather than assume a specific format. The java.time.format package has classes for such work.

Note the call to withLocale . The Locale specifies two elements, the cultural norms for the expected format and the human language to use for the names of the day and the month. If you do not specify a Locale, the JVM's current default Locale is implicitly applied. Better to be explicit, as the default can change at any moment.

DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate ( FormatStyle.SHORT ).withLocale ( Locale.US );
String output = today.format ( formatter );

Dump to console.

System.out.println ( "output: " + output );

output: 12/29/15

If you insist on a specific format, specify a coded pattern.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "MM/dd/yyyy" );
String output = today.format ( formatter );

output: 12/29/2015

Conversion

If you have a java.util.Date in hand, convert to java.time. An Instant is a moment on the timeline in UTC .

Instant instant = myJUDate.toInstant();

Assign the time zone by which you want to form a date, yielding a ZonedDateTime .

ZoneId zoneId = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId ) ;

Then ask for a LocalDate to be generated, its value extracted from the ZonedDateTime.

LocalDate localDate = zdt.toLocalDate();

try this...

  try {
        //parsing date format
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");

        String dealDateString = "02-Mar-2015";
        Date date = formatter.parse(dealDateString);
        TimeZone tz = TimeZone.getDefault();

        //converting date format for US
        SimpleDateFormat sdfAmerica = new SimpleDateFormat("MM/dd/yyyy");
        TimeZone tzInAmerica = TimeZone.getTimeZone("America/New_York");
        sdfAmerica.setTimeZone(tzInAmerica);

        String sDateInAmerica = sdfAmerica.format(date); // Convert to String first
        System.out.println("Date (String) : " + sDateInAmerica);

    } catch (Exception bug) {
        bug.printStackTrace();
    }

Can you try below code:

SimpleDateFormat ukDateFormat =  new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat usDateFormat = new SimpleDateFormat("MMM-dd-yyyy", Locale.US);

java.util.Date  dealDate = ukDateFormat.parse("02-Mar-2015");
String dateInUSFormat = usDateFormat.format(dealDate);
System.out.println(dd); // Here you have date String in US format.

Link has many examples on how to work with date conversion in Java

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