[英]Change date format in a Java string
我有一個代表日期的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.text.SimpleDateFormat
javadoc各個部分代表什么。 因此,例如M
代表月, m
代表分鍾。 此外,年份存在四位數yyyy
,而不是五位數yyyyy
。 仔細查看我在上面發布的代碼片段。
格式區分大小寫,因此使用 MM 表示月而不是 mm(這是表示分鍾)和 yyyy 作為參考,您可以使用以下備忘單。
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));
}
}
為什么不簡單地使用這個
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();
}
請參閱此處的“日期和時間模式”。 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 new date
,更多信息可以在Oracle 文檔中找到。
或者你可以試試舊的
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");
java.util
Date-Time API 及其格式化 API SimpleDateFormat
已過時且容易出錯。 建議完全停止使用它們並切換到現代 Date-Time API * 。
另外,下面引用的是來自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
關於解決方案的一些重要說明:
parse
和format
函數,在java.time
API 的情況下是DateTimeFormatter
)之外, java.time
使得在Date-Time 類型本身上調用parse
和format
函數成為可能。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,請檢查 通過 desugaring和How to use ThreeTenABP in Android Project 可用的 Java 8+ APIs 。
假設您要將 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;
}
此函數將返回您想要的答案。 如果您想自定義更多,只需從日期格式中添加或刪除組件。
我們可以將今天的日期轉換為'JUN 12, 2020'格式。
String.valueOf(DateFormat.getDateInstance().format(new Date())));
你有一些錯誤: SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
第一:應該是new SimpleDateFormat("yyyy-mm-dd");
//yyyy 4 不是 5 這個顯示 02011,而是 yyyy 它顯示 2011
第二:像這樣改變你的代碼new SimpleDateFormat("yyyy-MM-dd");
我希望能幫助你
/**
* 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;
}
SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.