从我的Date变量中删除时间 [英] Removing time from my Date variable
问题描述
唯一的问题是它保持返回默认时间,包括日期。
public Date getDob(){
String format = Integer.toString(this.dob);
try {
date = new SimpleDateFormat(ddMMyyyy)。parse(format);
} catch(ParseException e){
return null;
}
返回日期;
}
返回:1月16日星期六 00:00:00 CET 1999 [我想删除大胆的时间]
非常感谢您的帮助!
解决方案:
public String getDob(){
Date newDate = new Date(this.dob);
String date = new SimpleDateFormat(E MMM dd)。format(newDate);
返回日期;
}
一个java.util.Date按照定义的对象具有日期部分和日期部分。
Date-Time!= String
了解日期时间对象不是一个String。我们创建日期时间对象中包含的日期时间值的String表示形式,但这样做会生成与日期时间对象完全分离的新鲜的String对象。
LocalDate
如果您只想要一个日期,没有时间的概念,请使用在 Joda-Time 和新的 java.time包(灵感来自Joda-Time)。
Joda-Time
默认情况下,Joda-Time使用 ISO 8601 标准格式。如果您希望使用其他格式的字符串,请浏览 DateTimeFormat 类(DateTimeFormatters的工厂)。
Joda-Time 2.3中的示例代码。
String input =01021903; // 1903年2月1日。
DateTimeFormatter formatter = DateTimeFormat.forPattern(ddMMyyyy);
LocalDate dateOfBirth = formatter.parseLocalDate(input);
String outputStandard = dateOfBirth.toString(); //默认情况下,使用ISO 8601格式。
String outputCustom = formatter.print(dateOfBirth);
I have my Date of Birth variable which is initially of type int. It is then parsed toString() and parsed to Date with simpleDateFormat.
The only issue is that it keeps returning it's default time including the date.
public Date getDob(){
String format = Integer.toString(this.dob);
try{
date = new SimpleDateFormat("ddMMyyyy").parse(format);
}catch(ParseException e){
return null;
}
return date;
}
Returns: Sat Jan 16 00:00:00 CET 1999 [ I want to remove the bold time ]
Thank you very much for your help!
Solution:
public String getDob(){
Date newDate = new Date(this.dob);
String date = new SimpleDateFormat("E MMM dd").format(newDate);
return date;
}
A java.util.Date object by definition has both a date portion and a time-of-day portion.
Date-Time != String
Understand that a date-time object is not a String. We create String representations of the date-time value contained within a date-time object, but doing so is generating a fresh String object completely separate from the date-time object.
LocalDate
If you want only a date, without the notion of time-of-day, use the LocalDate class found in both Joda-Time and the new java.time package in Java 8 (inspired by Joda-Time).
Joda-Time
By default, Joda-Time uses the ISO 8601 standard formats. If you want Strings in other formats, explore the DateTimeFormat class (a factory of DateTimeFormatters).
Example code in Joda-Time 2.3.
String input = "01021903"; // First of February, 1903.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "ddMMyyyy" );
LocalDate dateOfBirth = formatter.parseLocalDate( input );
String outputStandard = dateOfBirth.toString(); // By default, the ISO 8601 format is used.
String outputCustom = formatter.print( dateOfBirth );
这篇关于从我的Date变量中删除时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!