I'd like to convert a date in date1 format to a date object in date2 format.
我想将date1格式的日期转换为date2格式的日期对象。
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd, yyyy");
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMdd");
Calendar cal = Calendar.getInstance();
cal.set(2012, 8, 21);
Date date = cal.getTime();
Date date1 = simpleDateFormat.parse(date);
Date date2 = simpleDateFormat.parse(date1);
println date1
println date2
9 个解决方案
#1
98
DateFormat originalFormat = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("yyyyMMdd");
Date date = originalFormat.parse("August 21, 2012");
String formattedDate = targetFormat.format(date); // 20120821
Also note that parse
takes a String
, not a Date
object, which is already parsed.
另请注意,parse采用的是String,而不是已经解析的Date对象。
#2
2
tl;dr
LocalDate.parse(
"January 08, 2017" ,
DateTimeFormatter.ofPattern( "MMMM dd, uuuu" , Locale.US )
).format( DateTimeFormatter.BASIC_ISO_DATE )
Using java.time
The Question and other Answers use troublesome old date-time classes, now legacy, supplanted by the java.time classes.
问题和其他答案使用麻烦的旧日期时间类,现在是旧的,由java.time类取代。
You have date-only values, so use a date-only class. The LocalDate
class represents a date-only value without time-of-day and without time zone.
您只有日期值,因此请使用仅限日期的类。 LocalDate类表示没有时间且没有时区的仅日期值。
String input = "January 08, 2017";
Locale l = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMMM dd, uuuu" , l );
LocalDate ld = LocalDate.parse( input , f );
Your desired output format is defined by the ISO 8601 standard. For a date-only value, the “expanded” format is YYYY-MM-DD such as 2017-01-08
and the “basic” format that minimizes the use of delimiters is YYYYMMDD such as 20170108
.
您所需的输出格式由ISO 8601标准定义。对于仅限日期的值,“扩展”格式为YYYY-MM-DD,例如2017-01-08,并且最小化分隔符使用的“基本”格式是YYYYMMDD,例如20170108。
I strongly suggest using the expanded format for readability. But if you insist on the basic format, that formatter is predefined as a constant on the DateTimeFormatter
class named BASIC_ISO_DATE
.
我强烈建议使用扩展格式以提高可读性。但是如果你坚持使用基本格式,则该格式化程序被预定义为DateTimeFormatter类的一个名为BASIC_ISO_DATE的常量。
String output = ld.format( DateTimeFormatter.BASIC_ISO_DATE );
See this code run live at IdeOne.com.
请参阅IdeOne.com上的此代码。
ld.toString(): 2017-01-08
output: 20170108
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧遗留日期时间类,如java.util.Date,Calendar和SimpleDateFormat。
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle教程。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310。
Where to obtain the java.time classes?
从哪里获取java.time类?
-
Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
带有捆绑实现的标准Java API的一部分。
Java 9增加了一些小功能和修复。
-
Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
许多java.time功能都被反向移植到ThreeTen-Backport中的Java 6和7。
-
Android
- The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
- See How to use ThreeTenABP….
ThreeTenABP项目特别适用于Android的ThreeTen-Backport(如上所述)。
请参见如何使用ThreeTenABP ....
Java SE 8和SE 9及更高版本内置。带有捆绑实现的标准Java API的一部分。 Java 9增加了一些小功能和修复。
Java SE 6和SE 7大部分java.time功能都被反向移植到ThreeTen-Backport中的Java 6和7。
Android ThreeTenABP项目专门针对Android调整ThreeTen-Backport(如上所述)。请参见如何使用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.
ThreeTen-Extra项目使用其他类扩展了java.time。该项目是未来可能添加到java.time的试验场。您可以在这里找到一些有用的课程,如Interval,YearWeek,YearQuarter等。
#3
2
Using Java 8, we can achieve this as follows:
使用Java 8,我们可以实现如下:
private static String convertDate(String strDate)
{
//for strdate = 2017 July 25
DateTimeFormatter f = new DateTimeFormatterBuilder().appendPattern("yyyy MMMM dd")
.toFormatter();
LocalDate parsedDate = LocalDate.parse(strDate, f);
DateTimeFormatter f2 = DateTimeFormatter.ofPattern("MM/d/yyyy");
String newDate = parsedDate.format(f2);
return newDate;
}
The output will be : "07/25/2017"
输出将是:“07/25/2017”
#4
1
Please refer to the following method. It takes your date String as argument1, you need to specify the existing format of the date as argument2, and the result (expected) format as argument 3.
请参考以下方法。它将您的日期String作为argument1,您需要将日期的现有格式指定为argument2,将结果(预期)格式指定为参数3。
Refer to this link to understand various formats: Available Date Formats
请参阅此链接以了解各种格式:可用日期格式
public static String formatDateFromOnetoAnother(String date,String givenformat,String resultformat) {
String result = "";
SimpleDateFormat sdf;
SimpleDateFormat sdf1;
try {
sdf = new SimpleDateFormat(givenformat);
sdf1 = new SimpleDateFormat(resultformat);
result = sdf1.format(sdf.parse(date));
}
catch(Exception e) {
e.printStackTrace();
return "";
}
finally {
sdf=null;
sdf1=null;
}
return result;
}
#5
0
Hope this will help someone.
希望这会对某人有所帮助。
public static String getDate(
String date, String currentFormat, String expectedFormat)
throws ParseException {
// Validating if the supplied parameters is null
if (date == null || currentFormat == null || expectedFormat == null ) {
return null;
}
// Create SimpleDateFormat object with source string date format
SimpleDateFormat sourceDateFormat = new SimpleDateFormat(currentFormat);
// Parse the string into Date object
Date dateObj = sourceDateFormat.parse(date);
// Create SimpleDateFormat object with desired date format
SimpleDateFormat desiredDateFormat = new SimpleDateFormat(expectedFormat);
// Parse the date into another format
return desiredDateFormat.format(dateObj).toString();
}
#6
0
Try this
This is the simplest way of changing one date format to another
这是将一种日期格式更改为另一种日期格式的最简单方法
public String changeDateFormatFromAnother(String date){
@SuppressLint("SimpleDateFormat") DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
@SuppressLint("SimpleDateFormat") DateFormat outputFormat = new SimpleDateFormat("dd MMMM yyyy");
String resultDate = "";
try {
resultDate=outputFormat.format(inputFormat.parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
return resultDate;
}
#7
0
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
String fromDateFormat = "dd/MM/yyyy";
String fromdate = 15/03/2018; //Take any date
String CheckFormat = "dd MMM yyyy";//take another format like dd/MMM/yyyy
String dateStringFrom;
Date DF = new Date();
try
{
//DateFormatdf = DateFormat.getDateInstance(DateFormat.SHORT);
DateFormat FromDF = new SimpleDateFormat(fromDateFormat);
FromDF.setLenient(false); // this is important!
Date FromDate = FromDF.parse(fromdate);
dateStringFrom = new
SimpleDateFormat(CheckFormat).format(FromDate);
DateFormat FromDF1 = new SimpleDateFormat(CheckFormat);
DF=FromDF1.parse(dateStringFrom);
System.out.println(dateStringFrom);
}
catch(Exception ex)
{
System.out.println("Date error");
}
output:- 15/03/2018
15 Mar 2018
#8
0
Kotlin equivalent of answer answered by João Silva
Kotlin相当于JoãoSilva回答的答案
fun getFormattedDate(originalFormat: SimpleDateFormat, targetFormat: SimpleDateFormat, inputDate: String): String {
return targetFormat.format(originalFormat.parse(inputDate))
}
Usage (In Android):
用法(在Android中):
getFormattedDate(
SimpleDateFormat(FormatUtils.d_MM_yyyy, Locale.getDefault()),
SimpleDateFormat(FormatUtils.d_MMM_yyyy, Locale.getDefault()),
dateOfTreatment
)
Note: Constant values:
注意:常量值:
// 25 Nov 2017
val d_MMM_yyyy = "d MMM yyyy"
// 25/10/2017
val d_MM_yyyy = "d/MM/yyyy"
#9
-1
//Convert input format 19-FEB-16 01.00.00.000000000 PM to 2016-02-19 01.00.000 PM
SimpleDateFormat inFormat = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.SSSSSSSSS aaa");
Date today = new Date();
Date d1 = inFormat.parse("19-FEB-16 01.00.00.000000000 PM");
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd hh.mm.ss.SSS aaa");
System.out.println("Out date ="+outFormat.format(d1));
#1
98
DateFormat originalFormat = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("yyyyMMdd");
Date date = originalFormat.parse("August 21, 2012");
String formattedDate = targetFormat.format(date); // 20120821
Also note that parse
takes a String
, not a Date
object, which is already parsed.
另请注意,parse采用的是String,而不是已经解析的Date对象。
#2
2
tl;dr
LocalDate.parse(
"January 08, 2017" ,
DateTimeFormatter.ofPattern( "MMMM dd, uuuu" , Locale.US )
).format( DateTimeFormatter.BASIC_ISO_DATE )
Using java.time
The Question and other Answers use troublesome old date-time classes, now legacy, supplanted by the java.time classes.
问题和其他答案使用麻烦的旧日期时间类,现在是旧的,由java.time类取代。
You have date-only values, so use a date-only class. The LocalDate
class represents a date-only value without time-of-day and without time zone.
您只有日期值,因此请使用仅限日期的类。 LocalDate类表示没有时间且没有时区的仅日期值。
String input = "January 08, 2017";
Locale l = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMMM dd, uuuu" , l );
LocalDate ld = LocalDate.parse( input , f );
Your desired output format is defined by the ISO 8601 standard. For a date-only value, the “expanded” format is YYYY-MM-DD such as 2017-01-08
and the “basic” format that minimizes the use of delimiters is YYYYMMDD such as 20170108
.
您所需的输出格式由ISO 8601标准定义。对于仅限日期的值,“扩展”格式为YYYY-MM-DD,例如2017-01-08,并且最小化分隔符使用的“基本”格式是YYYYMMDD,例如20170108。
I strongly suggest using the expanded format for readability. But if you insist on the basic format, that formatter is predefined as a constant on the DateTimeFormatter
class named BASIC_ISO_DATE
.
我强烈建议使用扩展格式以提高可读性。但是如果你坚持使用基本格式,则该格式化程序被预定义为DateTimeFormatter类的一个名为BASIC_ISO_DATE的常量。
String output = ld.format( DateTimeFormatter.BASIC_ISO_DATE );
See this code run live at IdeOne.com.
请参阅IdeOne.com上的此代码。
ld.toString(): 2017-01-08
output: 20170108
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧遗留日期时间类,如java.util.Date,Calendar和SimpleDateFormat。
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle教程。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310。
Where to obtain the java.time classes?
从哪里获取java.time类?
-
Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
带有捆绑实现的标准Java API的一部分。
Java 9增加了一些小功能和修复。
-
Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
许多java.time功能都被反向移植到ThreeTen-Backport中的Java 6和7。
-
Android
- The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
- See How to use ThreeTenABP….
ThreeTenABP项目特别适用于Android的ThreeTen-Backport(如上所述)。
请参见如何使用ThreeTenABP ....
Java SE 8和SE 9及更高版本内置。带有捆绑实现的标准Java API的一部分。 Java 9增加了一些小功能和修复。
Java SE 6和SE 7大部分java.time功能都被反向移植到ThreeTen-Backport中的Java 6和7。
Android ThreeTenABP项目专门针对Android调整ThreeTen-Backport(如上所述)。请参见如何使用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.
ThreeTen-Extra项目使用其他类扩展了java.time。该项目是未来可能添加到java.time的试验场。您可以在这里找到一些有用的课程,如Interval,YearWeek,YearQuarter等。
#3
2
Using Java 8, we can achieve this as follows:
使用Java 8,我们可以实现如下:
private static String convertDate(String strDate)
{
//for strdate = 2017 July 25
DateTimeFormatter f = new DateTimeFormatterBuilder().appendPattern("yyyy MMMM dd")
.toFormatter();
LocalDate parsedDate = LocalDate.parse(strDate, f);
DateTimeFormatter f2 = DateTimeFormatter.ofPattern("MM/d/yyyy");
String newDate = parsedDate.format(f2);
return newDate;
}
The output will be : "07/25/2017"
输出将是:“07/25/2017”
#4
1
Please refer to the following method. It takes your date String as argument1, you need to specify the existing format of the date as argument2, and the result (expected) format as argument 3.
请参考以下方法。它将您的日期String作为argument1,您需要将日期的现有格式指定为argument2,将结果(预期)格式指定为参数3。
Refer to this link to understand various formats: Available Date Formats
请参阅此链接以了解各种格式:可用日期格式
public static String formatDateFromOnetoAnother(String date,String givenformat,String resultformat) {
String result = "";
SimpleDateFormat sdf;
SimpleDateFormat sdf1;
try {
sdf = new SimpleDateFormat(givenformat);
sdf1 = new SimpleDateFormat(resultformat);
result = sdf1.format(sdf.parse(date));
}
catch(Exception e) {
e.printStackTrace();
return "";
}
finally {
sdf=null;
sdf1=null;
}
return result;
}
#5
0
Hope this will help someone.
希望这会对某人有所帮助。
public static String getDate(
String date, String currentFormat, String expectedFormat)
throws ParseException {
// Validating if the supplied parameters is null
if (date == null || currentFormat == null || expectedFormat == null ) {
return null;
}
// Create SimpleDateFormat object with source string date format
SimpleDateFormat sourceDateFormat = new SimpleDateFormat(currentFormat);
// Parse the string into Date object
Date dateObj = sourceDateFormat.parse(date);
// Create SimpleDateFormat object with desired date format
SimpleDateFormat desiredDateFormat = new SimpleDateFormat(expectedFormat);
// Parse the date into another format
return desiredDateFormat.format(dateObj).toString();
}
#6
0
Try this
This is the simplest way of changing one date format to another
这是将一种日期格式更改为另一种日期格式的最简单方法
public String changeDateFormatFromAnother(String date){
@SuppressLint("SimpleDateFormat") DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
@SuppressLint("SimpleDateFormat") DateFormat outputFormat = new SimpleDateFormat("dd MMMM yyyy");
String resultDate = "";
try {
resultDate=outputFormat.format(inputFormat.parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
return resultDate;
}
#7
0
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
String fromDateFormat = "dd/MM/yyyy";
String fromdate = 15/03/2018; //Take any date
String CheckFormat = "dd MMM yyyy";//take another format like dd/MMM/yyyy
String dateStringFrom;
Date DF = new Date();
try
{
//DateFormatdf = DateFormat.getDateInstance(DateFormat.SHORT);
DateFormat FromDF = new SimpleDateFormat(fromDateFormat);
FromDF.setLenient(false); // this is important!
Date FromDate = FromDF.parse(fromdate);
dateStringFrom = new
SimpleDateFormat(CheckFormat).format(FromDate);
DateFormat FromDF1 = new SimpleDateFormat(CheckFormat);
DF=FromDF1.parse(dateStringFrom);
System.out.println(dateStringFrom);
}
catch(Exception ex)
{
System.out.println("Date error");
}
output:- 15/03/2018
15 Mar 2018
#8
0
Kotlin equivalent of answer answered by João Silva
Kotlin相当于JoãoSilva回答的答案
fun getFormattedDate(originalFormat: SimpleDateFormat, targetFormat: SimpleDateFormat, inputDate: String): String {
return targetFormat.format(originalFormat.parse(inputDate))
}
Usage (In Android):
用法(在Android中):
getFormattedDate(
SimpleDateFormat(FormatUtils.d_MM_yyyy, Locale.getDefault()),
SimpleDateFormat(FormatUtils.d_MMM_yyyy, Locale.getDefault()),
dateOfTreatment
)
Note: Constant values:
注意:常量值:
// 25 Nov 2017
val d_MMM_yyyy = "d MMM yyyy"
// 25/10/2017
val d_MM_yyyy = "d/MM/yyyy"
#9
-1
//Convert input format 19-FEB-16 01.00.00.000000000 PM to 2016-02-19 01.00.000 PM
SimpleDateFormat inFormat = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.SSSSSSSSS aaa");
Date today = new Date();
Date d1 = inFormat.parse("19-FEB-16 01.00.00.000000000 PM");
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd hh.mm.ss.SSS aaa");
System.out.println("Out date ="+outFormat.format(d1));