问题描述
我正在寻找一种简单的方法来从用户可能输入的任何时间输入生成MySQL DATETIME。 PHP使用它的strtotime()函数可以轻松实现:
strtotime('2004-02-12T15:19:21 + 00:00'); p>
strtotime('Thu,21 Dec 2000 16:01:07 +0200');
strtotime('Monday ,1月1日);
strtotime('tomorrow');
strtotime(' - 1 week 2天4小时2秒');
输出:
2004-02-12 07:02:21
2000-12-21 06:12:07
2009-01-01 12:01:00
2009-02-12 12:02:00
2009-02-06 09:02:41
我希望在Java中使用
回复ChssPly76。这是我的解决方案,尽管处理以下格式的日期很困难:5 Aug 2009 07:27:51 GMT。也许有一种方法允许它在解析异常的情况下容易处理其他格式?
public static String stringToDateTime(String string){
SimpleDateFormat sdf = new SimpleDateFormat(d MMM yyyy HH:mm:ss z);
日期日期;
String sqlDate;
try {
date = sdf.parse(string);
SimpleDateFormat sqlFormat = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss);
sqlDate = sqlFormat.format(date);
}
catch(ParseException ex){
sqlDate = string;
}
return sqlDate;
}
I'm looking for an easy way to generate a MySQL DATETIME from any type of time input a user may enter. PHP makes it easy with its strtotime() function that can do:
strtotime(’2004-02-12T15:19:21+00:00′);
strtotime(’Thu, 21 Dec 2000 16:01:07 +0200′);
strtotime(’Monday, January 1st’);
strtotime(’tomorrow’);
strtotime(’-1 week 2 days 4 hours 2 seconds’);
Outputs:
2004-02-12 07:02:21
2000-12-21 06:12:07
2009-01-01 12:01:00
2009-02-12 12:02:00
2009-02-06 09:02:41
I want this in Java!
Thanks for the quick reply ChssPly76. Here's my solution, although it's hard coded to handle dates coming in this format: "5 Aug 2009 07:27:51 GMT". Perhaps there is a way to allow it to easily handle other formats in case of a parse exception?
public static String stringToDateTime(String string) {
SimpleDateFormat sdf = new SimpleDateFormat("d MMM yyyy HH:mm:ss z");
Date date;
String sqlDate;
try {
date = sdf.parse(string);
SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sqlDate = sqlFormat.format(date);
}
catch(ParseException ex) {
sqlDate = string;
}
return sqlDate;
}
这篇关于PHP中的strtotime()在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!