更改YYYY/MM/DD->MM/DD/YYYY java [英] Changing YYYY/MM/DD -> MM/DD/YYYY java
问题描述
我希望将日期格式更改为MM/DD/YYYY,当前为YYYY/MM/DD.
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
顺便说一下,我不熟悉的简单日期格式类和日期格式类,并且尝试实现它们均未成功.
推荐答案
只需使用 SimpleDateFormat
将 String
转换为 Date
.无需麻烦的 Calendar
API.
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);
在整个代码中使用此 Date
对象.每当您需要向人类展示 Date
对象时,只需使用另一个 SimpleDateFormat
:
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);
这篇关于更改YYYY/MM/DD->MM/DD/YYYY java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!