我有一个代表日期的 String
。
String date_s = "2011-01-18 00:00:00.0";
我想将其转换为 Date
并以 YYYY-MM-DD
格式输出。
2011-01-18
我怎样才能做到这一点?
好的,根据我在下面检索到的答案,这是我尝试过的:
String date_s = " 2011-01-18 00:00:00.0";
SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss");
Date date = dt.parse(date_s);
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
System.out.println(dt1.format(date));
但它输出 02011-00-1
而不是所需的 2011-01-18
。我究竟做错了什么?
使用 LocalDateTime#parse()
(如果字符串恰好包含时区部分,则使用 ZonedDateTime#parse()
)将特定模式中的 String
解析为 LocalDateTime
。
String oldstring = "2011-01-18 00:00:00.0";
LocalDateTime datetime = LocalDateTime.parse(oldstring, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));
使用 LocalDateTime#format()
(或 ZonedDateTime#format()
)以特定模式将 LocalDateTime
格式化为 String
。
String newstring = datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(newstring); // 2011-01-18
或者,当您还没有使用 Java 8 时,使用 SimpleDateFormat#parse()
将特定模式的 String
解析为 Date
。
String oldstring = "2011-01-18 00:00:00.0";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(oldstring);
使用 SimpleDateFormat#format()
以特定模式将 Date
格式化为 String
。
String newstring = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(newstring); // 2011-01-18
也可以看看:
Java 字符串到日期的转换
更新:根据您的失败尝试:模式区分大小写。阅读java.text.SimpleDateFormat
javadoc各个部分的含义。例如 M
代表月,m
代表分钟。此外,年份存在四位数 yyyy
,而不是五位数 yyyyy
。仔细查看我在上面发布的代码片段。
格式区分大小写,因此使用 MM 表示月份而不是 mm(这是分钟)和 yyyy 对于 Reference,您可以使用以下备忘单。
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day name in week Text Tuesday; Tue
u Day number of week (1 = Monday, ..., 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
例子:
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"h:mm a" 12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" 2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u" 2001-W27-3
答案当然是创建一个 SimpleDateFormat 对象并使用它来将字符串解析为日期并将日期格式化为字符串。如果您尝试过 SimpleDateFormat 但它不起作用,那么请显示您的代码以及您可能收到的任何错误。
附录:字符串格式中的“mm”与“MM”不同。用 MM 表示月,用 mm 表示分钟。此外,yyyyy 与 yyyy 不同。例如,:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FormateDate {
public static void main(String[] args) throws ParseException {
String date_s = "2011-01-18 00:00:00.0";
// *** note that it's "yyyy-MM-dd hh:mm:ss" not "yyyy-mm-dd hh:mm:ss"
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = dt.parse(date_s);
// *** same for the format String below
SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(dt1.format(date));
}
}
hh
将为您提供 1-12 范围内的小时,除了打印/解析 AM
或 PM
之外,您还需要使用 a
。要打印/解析 0-23 范围内的小时,请使用 HH
。
为什么不简单地使用它
Date convertToDate(String receivedDate) throws ParseException{
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = formatter.parse(receivedDate);
return date;
}
此外,这是另一种方式:
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String requiredDate = df.format(new Date()).toString();
或者
Date requiredDate = df.format(new Date());
在 Java 8 及更高版本中使用 java.time
包:
String date = "2011-01-18 00:00:00.0";
TemporalAccessor temporal = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss.S")
.parse(date); // use parse(date, LocalDateTime::from) to get LocalDateTime
String output = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(temporal);
[编辑以包括 BalusC 的更正] SimpleDateFormat 类应该可以解决问题:
String pattern = "yyyy-MM-dd HH:mm:ss.S";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date = format.parse("2011-01-18 00:00:00.0");
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
DD
代表“一年中的一天”,而不是“一个月中的一天”。 hh
代表“上午/下午 (1-12) 中的小时”,而不是“一天中的小时 (0-23)”。
请参阅此处的“日期和时间模式”。 http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;
public class DateConversionExample{
public static void main(String arg[]){
try{
SimpleDateFormat sourceDateFormat = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
Date date = sourceDateFormat.parse("2011-01-18 00:00:00.0");
SimpleDateFormat targetDateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(targetDateFormat.format(date));
}catch(ParseException e){
e.printStackTrace();
}
}
}
其他答案是正确的,基本上你的模式中有错误数量的“y”字符。
时区
还有一个问题……您没有解决时区问题。如果您打算使用 UTC,那么您应该这么说。如果不是,则答案不完整。如果您想要的只是没有时间的日期部分,那么没问题。但是,如果您进行可能涉及时间的进一步工作,那么您应该指定一个时区。
乔达时间
这是相同类型的代码,但使用了第三方开源 Joda-Time 2.3 库
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
String date_s = "2011-01-18 00:00:00.0";
org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern( "yyyy-MM-dd' 'HH:mm:ss.SSS" );
// By the way, if your date-time string conformed strictly to ISO 8601 including a 'T' rather than a SPACE ' ', you could
// use a formatter built into Joda-Time rather than specify your own: ISODateTimeFormat.dateHourMinuteSecondFraction().
// Like this:
//org.joda.time.DateTime dateTimeInUTC = org.joda.time.format.ISODateTimeFormat.dateHourMinuteSecondFraction().withZoneUTC().parseDateTime( date_s );
// Assuming the date-time string was meant to be in UTC (no time zone offset).
org.joda.time.DateTime dateTimeInUTC = formatter.withZoneUTC().parseDateTime( date_s );
System.out.println( "dateTimeInUTC: " + dateTimeInUTC );
System.out.println( "dateTimeInUTC (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInUTC ) );
System.out.println( "" ); // blank line.
// Assuming the date-time string was meant to be in Kolkata time zone (formerly known as Calcutta). Offset is +5:30 from UTC (note the half-hour).
org.joda.time.DateTimeZone kolkataTimeZone = org.joda.time.DateTimeZone.forID( "Asia/Kolkata" );
org.joda.time.DateTime dateTimeInKolkata = formatter.withZone( kolkataTimeZone ).parseDateTime( date_s );
System.out.println( "dateTimeInKolkata: " + dateTimeInKolkata );
System.out.println( "dateTimeInKolkata (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInKolkata ) );
// This date-time in Kolkata is a different point in the time line of the Universe than the dateTimeInUTC instance created above. The date is even different.
System.out.println( "dateTimeInKolkata adjusted to UTC: " + dateTimeInKolkata.toDateTime( org.joda.time.DateTimeZone.UTC ) );
运行时…
dateTimeInUTC: 2011-01-18T00:00:00.000Z
dateTimeInUTC (date only): 2011-01-18
dateTimeInKolkata: 2011-01-18T00:00:00.000+05:30
dateTimeInKolkata (date only): 2011-01-18
dateTimeInKolkata adjusted to UTC: 2011-01-17T18:30:00.000Z
try
{
String date_s = "2011-01-18 00:00:00.0";
SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date tempDate=simpledateformat.parse(date_s);
SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Output date is = "+outputDateFormat.format(tempDate));
} catch (ParseException ex)
{
System.out.println("Parse Exception");
}
您可以使用:
Date yourDate = new Date();
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
String date = DATE_FORMAT.format(yourDate);
它完美地工作!
public class SystemDateTest {
String stringDate;
public static void main(String[] args) {
SystemDateTest systemDateTest = new SystemDateTest();
// format date into String
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
systemDateTest.setStringDate(simpleDateFormat.format(systemDateTest.getDate()));
System.out.println(systemDateTest.getStringDate());
}
public Date getDate() {
return new Date();
}
public String getStringDate() {
return stringDate;
}
public void setStringDate(String stringDate) {
this.stringDate = stringDate;
}
}
String str = "2000-12-12";
Date dt = null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try
{
dt = formatter.parse(str);
}
catch (Exception e)
{
}
JOptionPane.showMessageDialog(null, formatter.format(dt));
您也可以使用 substring()
String date_s = "2011-01-18 00:00:00.0";
date_s.substring(0,10);
如果您想在日期前留一个空格,请使用
String date_s = " 2011-01-18 00:00:00.0";
date_s.substring(1,11);
您可以尝试 Java 8 新的date
,更多信息可以在 Oracle documentation 上找到。
或者你可以试试旧的
public static Date getDateFromString(String format, String dateStr) {
DateFormat formatter = new SimpleDateFormat(format);
Date date = null;
try {
date = (Date) formatter.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public static String getDate(Date date, String dateFormat) {
DateFormat formatter = new SimpleDateFormat(dateFormat);
return formatter.format(date);
}
private SimpleDateFormat dataFormat = new SimpleDateFormat("dd/MM/yyyy");
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if(value instanceof Date) {
value = dataFormat.format(value);
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
};
删除格式提供的一个 y 格式:
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
它应该是:
SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");
DateTimeFormatter
还是使用过时的 SimpleDateFormat
)。
我们可以将今天的日期转换为“2020 年 6 月 12 日”的格式。
String.valueOf(DateFormat.getDateInstance().format(new Date())));
/**
* Method will take Date in "MMMM, dd yyyy HH:mm:s" format and return time difference like added: 3 min ago
*
* @param date : date in "MMMM, dd yyyy HH:mm:s" format
* @return : time difference
*/
private String getDurationTimeStamp(String date) {
String timeDifference = "";
//date formatter as per the coder need
SimpleDateFormat sdf = new SimpleDateFormat("MMMM, dd yyyy HH:mm:s");
TimeZone timeZone = TimeZone.getTimeZone("EST");
sdf.setTimeZone(timeZone);
Date startDate = null;
try {
startDate = sdf.parse(date);
} catch (ParseException e) {
MyLog.printStack(e);
}
//end date will be the current system time to calculate the lapse time difference
Date endDate = new Date();
//get the time difference in milliseconds
long duration = endDate.getTime() - startDate.getTime();
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);
if (diffInDays >= 365) {
int year = (int) (diffInDays / 365);
timeDifference = year + mContext.getString(R.string.year_ago);
} else if (diffInDays >= 30) {
int month = (int) (diffInDays / 30);
timeDifference = month + mContext.getString(R.string.month_ago);
}
//if days are not enough to create year then get the days
else if (diffInDays >= 1) {
timeDifference = diffInDays + mContext.getString(R.string.day_ago);
}
//if days value<1 then get the hours
else if (diffInHours >= 1) {
timeDifference = diffInHours + mContext.getString(R.string.hour_ago);
}
//if hours value<1 then get the minutes
else if (diffInMinutes >= 1) {
timeDifference = diffInMinutes + mContext.getString(R.string.min_ago);
}
//if minutes value<1 then get the seconds
else if (diffInSeconds >= 1) {
timeDifference = diffInSeconds + mContext.getString(R.string.sec_ago);
} else if (timeDifference.isEmpty()) {
timeDifference = mContext.getString(R.string.now);
}
return mContext.getString(R.string.added) + " " + timeDifference;
}
java.time
java.util
日期时间 API 及其格式化 API SimpleDateFormat
已过时且容易出错。建议完全停止使用它们并切换到 modern Date-Time API*。
此外,下面引用的是来自 home page of Joda-Time 的通知:
请注意,从 Java SE 8 开始,用户被要求迁移到 java.time (JSR-310) - JDK 的核心部分,它取代了这个项目。
使用现代日期时间 API java.time
的解决方案:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDate = "2011-01-18 00:00:00.0";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d H:m:s.S", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(strDate, dtfInput);
// Alternatively, the old way:
// LocalDateTime ldt = dtfInput.parse(strDate, LocalDateTime::from);
LocalDate date = ldt.toLocalDate();
System.out.println(date);
}
}
输出:
2011-01-18
关于解决方案的一些重要说明:
java.time 使得在 Date-Time 类型本身上调用解析和格式化函数成为可能,除了旧方式(即在格式化程序类型上调用解析和格式化函数,在 java.time API 的情况下是 DateTimeFormatter)。现代日期时间 API 基于 ISO 8601,并且不需要明确使用 DateTimeFormatter 对象,只要日期时间字符串符合 ISO 8601 标准,例如我没有使用 DateTimeFormatter 作为输出,因为 LocalDate#toString 已经返回所需格式的字符串。在这里,您可以使用 y 代替 u,但我更喜欢 u 而不是 y。
从 Trail: Date Time 了解有关现代日期时间 API 的更多信息。
* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 & 7. 如果您正在为一个 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring 和 How to use ThreeTenABP in Android Project。
假设您想将 2019-12-20 10:50 AM GMT+6:00 更改为 2019-12-20 10:50 AM 首先您必须了解日期格式第一个日期格式是 yyyy-MM-dd hh :mm a zzz 和第二个日期格式将是 yyyy-MM-dd hh:mm a
只需从此函数返回一个字符串,例如。
public String convertToOnlyDate(String currentDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a ");
Date date;
String dateString = "";
try {
date = dateFormat.parse(currentDate);
System.out.println(date.toString());
dateString = dateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return dateString;
}
此功能将返回您想要的答案。如果您想自定义更多,只需从日期格式中添加或删除组件。
你有一些错误: SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
首先:应该是 new SimpleDateFormat("yyyy-mm-dd");
//yyyy 4 而不是 5 这个显示 02011,但是 yyyy 它显示 2011
第二:像这样更改您的代码new SimpleDateFormat("yyyy-MM-dd");
我希望能帮助你
SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");
DateTimeFormatter
和 DateTimeFormatterBuilder
。在 2019 年建议 SimpleDateFormat
是糟糕的建议。
hh
为一小时。
不定期副业成功案例分享