英文:
Datetime format in java for date like 'Jun 3, 2020 5:04:05 PM'
问题
在Java中是否有一种格式用于解析日期,例如像'Jun 3, 2020 5:04:05 PM'这样的格式?因为我正在使用JEE创建一个应用程序,在持久化数据时,我的日志文件中出现了以下消息:<Text 'Jun 3, 2020 5:04:05 PM' 无法在索引0处解析>。
英文:
Is there an format in java for parsing date such as 'Jun 3, 2020 5:04:05 PM' because i'm creating an app in JEE and i got ths message <Text 'Jun 3, 2020 5:04:05 PM' could not be parsed at index 0> in my log file when persisting data
答案1
得分: 2
I recommend you use java.time.LocalDateTime
and DateTimeFormatter.ofPattern
instead of using the outdated java.util.Date
and SimpleDateFormat
. Check this to learn more about the modern date/time API.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Define format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d, yyyy h:mm:ss a", Locale.US);
// Date/time string
String strDate = "Jun 3, 2020 5:04:05 PM";
// Parse the date/time string into LocalDateTime
LocalDateTime ldt = LocalDateTime.parse(strDate, formatter);
// Display ldt.toString()
System.out.println(ldt);
// Display `ldt` in the specified format
System.out.println(formatter.format(ldt));
}
}
Output:
2020-06-03T17:04:05
Jun 3, 2020 5:04:05 PM
英文:
I recommend you use java.time.LocalDateTime
and DateTimeFormatter.ofPattern
instead of using the outdated java.util.Date
and SimpleDateFormat
. Check this to learn more about the modern date/time API.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Define format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d, yyyy h:mm:ss a", Locale.US);
// Date/time string
String strDate = "Jun 3, 2020 5:04:05 PM";
// Parse the date/time string into LocalDateTime
LocalDateTime ldt = LocalDateTime.parse(strDate, formatter);
// Display ldt.toString()
System.out.println(ldt);
// Display `ldt` in the specified format
System.out.println(formatter.format(ldt));
}
}
Output:
2020-06-03T17:04:05
Jun 3, 2020 5:04:05 PM
答案2
得分: 1
如果我理解你的意思正确的话:
String dString = "2020年6月3日 下午5:04:05";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy年M月d日 a h:mm:ss", Locale.CHINA);
Date date = formatter.parse(dString);
编辑:
处理地区信息:
new SimpleDateFormat("yyyy年M月d日 a h:mm:ss", Locale.US);
你也可以查看 LocalDateTime
和 DateTimeFormatter
。
英文:
If I understand you correctly:
String dString = "Jun 3, 2020 5:04:05 PM"
SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss aa");
Date date = formater.parse(dString);
EDIT:
Dealing with locale:
new SimpleDateFormat("MMM dd, yyyy HH:mm:ss aa", Locale.US)
You can also look at LocalDateTime
and DateTimeFormatter
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论