user1283885
user1283885

Reputation: 1263

Changing YYYY/MM/DD -> MM/DD/YYYY java

I wish to change my date formatting to MM/DD/YYYY, currently it is in YYYY/MM/DD.

I tried researching it, but to my irony, it is always the other way around. Now one might say try it backwards try working from there, but it didn't work.

My class for calling all the things:

import java.util.*;
import java.text.*;

class Driver {   
   public static void main (String[] args) {    
       Kid kid;
       Node list = new Node(); 

       kid = createKid("Lexie", 2.6, "11/5/2009"); 
       insertEnd(list, kid);
       kid = createKid ("Sally", 2.3, "4/8/2009"); 
       insertEnd(list, kid);
       kid = createKid ("Joe", 2.7, "6/16/2009");
       insertEnd(list, kid);
       kid = createKid ("Bob", 2.2, "1/16/2009");
       insertEnd(list, kid);
       kid = createKid ("Tom", 3.1, "8/16/2009");
       insertEnd(list, kid);
       printList(list);
   } //end main method

   public static Kid createKid(String name, double height, String date) {
       return new Kid(name, height, date);
   }

} //end class     


import java.util.*; 
import java.text.SimpleDateFormat;
import java.io.*;
class Kid {  
    String name; 
    double height; 
    GregorianCalendar bDay; 

    ...
    /**
     * Second constructor for kid
     * Setting instances to equal the constructors of this
     * @param 1: Setting n (aka name,   but it was taken) to equal the instance var of name
     * @param 2: Setting h (aka height, but it was taken) to equal the instance var of height
     * @param 3: Setting date to equal the instance var of bDay with some modifications
     */
    public Kid (String n, double h, String date) {
        StringTokenizer st = new StringTokenizer(date, "/");
        this.name = n;
        this.height = h;
        this.bDay = new GregorianCalendar(Integer.parseInt(st.nextToken()), 
        Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
    }

    /**
     * public String toString() { 
     * Converting Java language to English language
     */
    public String toString() {

        return (this.name + ", Height: " + this.height + "ft., Born: "
        +       this.bDay.get(Calendar.DATE) + "/" + this.bDay.get(Calendar.MONTH) 
        + "/" + this.bDay.get(Calendar.YEAR));

    }
} //end class 

By the way, the Simple Date Format class and Date Format class I am unfamiliar with and have unsuccessfully tried to implement them.

Upvotes: 2

Views: 914

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 338730

tl;dr

String output = LocalDate.parse( "2012/06/05".replace( "/" , "-" ) ).format( DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( Locale.US ) ) ;

Details

The Answer by BalusC is correct but now outdated.

The old date-time classes such as Date and Calendar are now legacy. Use the java.time classes instead.

ISO 8601

Your input string is nearly compliant with the ISO 8601 standard. Just replace the slash characters with hyphens. The java.time classes parse/generate strings in ISO 8601 formats by default without needing to define a formatting pattern.

String input = "2012/06/05".replace( "/" , "-" );

LocalDate

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

LocalDate ld = LocalDate.parse( input );

To generate output in ISO 8601 format, simply call toString.

String output = ld.toString();

To generate a String in other formats, use DateTimeFormatter. Usually best to let that class automatically localize for you by specifying a Locale. The Locale determines (a) human language for translation, (b) cultural norms for issues such as capitalization, punctuation, ordering of parts.

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ) ;
f = f.withLocale( Locale.US );  // Or Locale.CANADA_FRENCH etc.
String output = ld.format( f );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

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.

Upvotes: 0

BalusC
BalusC

Reputation: 1108742

Just use SimpleDateFormat to convert String to Date. No need to hassle with painful Calendar API.

String dateString = "2012/06/05";
Date date = new SimpleDateFormat("yyyy/MM/dd").parse(dateString);

Use this Date object throughout your code instead. Whenever you need to present the Date object to humans, just use another SimpleDateFormat:

String dateString = new SimpleDateFormat("MM/dd/yyyy").format(date);

Upvotes: 7

Related Questions