在Java中将字符串日期转换为美国格式 [英] converting a string date into US format in java
问题描述
我有以下代码,其中日期以字符串类型出现,因此我必须将其设置为美国格式
,因此在下面已显示了它
I have the below code in which date come as string type and I have to set it in US format so below I have shown it
private static final SimpleDateFormat usOutputDate = new SimpleDateFormat("MM/dd/yyyy");
,在一个方法中,我编写了以下代码,并在 dealDateString 的值是
2015年3月2日
and inside a method I have written the below code and inside dealDateString
the value is coming as 02-Mar-2015
// dealDateString = 02-Mar-2015
java.util.Date dealDate = extractDate(dealDateString);
//here its value get converted in US format that is 03/02/2015
String dd = usOutputDate.format(dealDate);
DateFormat format = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
// ***issue comes here as it get back converted in US format ***
java.util.Date date = format.parse(dd);
brokerInvoiceLineItem.setDealDate(new Date(date));
如上面的代码所示,它的值在 String dd
是 03/02/2015
,但问题出在格式变量中,其中
的值转换为英国格式,我不希望这样做,请告知我如何将其转换为英国格式,因为它已经将
转换为以前存储在 String dd
中的美国格式。
as shown in the above code that's it value inside String dd
is 03/02/2015
but the issue comes at format variable where
its value get converted back in UK format which i do not want please advise how can i convert it in UK format as it
is already converted in US format previously stored inside String dd
.
推荐答案
尝试一下...
try {
//parsing date format
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dealDateString = "02-Mar-2015";
Date date = formatter.parse(dealDateString);
TimeZone tz = TimeZone.getDefault();
//converting date format for US
SimpleDateFormat sdfAmerica = new SimpleDateFormat("MM/dd/yyyy");
TimeZone tzInAmerica = TimeZone.getTimeZone("America/New_York");
sdfAmerica.setTimeZone(tzInAmerica);
String sDateInAmerica = sdfAmerica.format(date); // Convert to String first
System.out.println("Date (String) : " + sDateInAmerica);
} catch (Exception bug) {
bug.printStackTrace();
}
这篇关于在Java中将字符串日期转换为美国格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!