什么是最好的方法转换格式的字符串' 1月2日,2010年'到一个日期在Java?
最后,我希望将月、日和年分解为整数,以便我可以使用
Date date = new Date();
date.setMonth()..
date.setYear()..
date.setDay()..
date.setlong currentTime = date.getTime();
将日期转换为时间。
什么是最好的方法转换格式的字符串' 1月2日,2010年'到一个日期在Java?
最后,我希望将月、日和年分解为整数,以便我可以使用
Date date = new Date();
date.setMonth()..
date.setYear()..
date.setDay()..
date.setlong currentTime = date.getTime();
将日期转换为时间。
当前回答
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date1 = null;
Date date2 = null;
try {
date1 = dateFormat.parse(t1);
date2 = dateFormat.parse(t2);
} catch (ParseException e) {
e.printStackTrace();
}
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String StDate = formatter.format(date1);
String edDate = formatter.format(date2);
System.out.println("ST "+ StDate);
System.out.println("ED "+ edDate);
其他回答
字符串到日期的转换:
private Date StringtoDate(String date) throws Exception {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date sqlDate = null;
if( !date.isEmpty()) {
try {
java.util.Date normalDate = sdf1.parse(date);
sqlDate = new java.sql.Date(normalDate.getTime());
} catch (ParseException e) {
throw new Exception("Not able to Parse the date", e);
}
}
return sqlDate;
}
啊,又是Java Date的讨论。为了处理日期操作,我们使用date、Calendar、GregorianCalendar和SimpleDateFormat。例如,用你一月份的日期作为输入:
Calendar mydate = new GregorianCalendar();
String mystring = "January 2, 2010";
Date thedate = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(mystring);
mydate.setTime(thedate);
//breakdown
System.out.println("mydate -> "+mydate);
System.out.println("year -> "+mydate.get(Calendar.YEAR));
System.out.println("month -> "+mydate.get(Calendar.MONTH));
System.out.println("dom -> "+mydate.get(Calendar.DAY_OF_MONTH));
System.out.println("dow -> "+mydate.get(Calendar.DAY_OF_WEEK));
System.out.println("hour -> "+mydate.get(Calendar.HOUR));
System.out.println("minute -> "+mydate.get(Calendar.MINUTE));
System.out.println("second -> "+mydate.get(Calendar.SECOND));
System.out.println("milli -> "+mydate.get(Calendar.MILLISECOND));
System.out.println("ampm -> "+mydate.get(Calendar.AM_PM));
System.out.println("hod -> "+mydate.get(Calendar.HOUR_OF_DAY));
然后你可以用类似这样的东西来操纵它:
Calendar now = Calendar.getInstance();
mydate.set(Calendar.YEAR,2009);
mydate.set(Calendar.MONTH,Calendar.FEBRUARY);
mydate.set(Calendar.DAY_OF_MONTH,25);
mydate.set(Calendar.HOUR_OF_DAY,now.get(Calendar.HOUR_OF_DAY));
mydate.set(Calendar.MINUTE,now.get(Calendar.MINUTE));
mydate.set(Calendar.SECOND,now.get(Calendar.SECOND));
// or with one statement
//mydate.set(2009, Calendar.FEBRUARY, 25, now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), now.get(Calendar.SECOND));
System.out.println("mydate -> "+mydate);
System.out.println("year -> "+mydate.get(Calendar.YEAR));
System.out.println("month -> "+mydate.get(Calendar.MONTH));
System.out.println("dom -> "+mydate.get(Calendar.DAY_OF_MONTH));
System.out.println("dow -> "+mydate.get(Calendar.DAY_OF_WEEK));
System.out.println("hour -> "+mydate.get(Calendar.HOUR));
System.out.println("minute -> "+mydate.get(Calendar.MINUTE));
System.out.println("second -> "+mydate.get(Calendar.SECOND));
System.out.println("milli -> "+mydate.get(Calendar.MILLISECOND));
System.out.println("ampm -> "+mydate.get(Calendar.AM_PM));
System.out.println("hod -> "+mydate.get(Calendar.HOUR_OF_DAY));
虽然有些答案在技术上是正确的,但它们并不可取。
The java.util.Date & Calendar classes are notoriously troublesome. Because of flaws in design and implementation, avoid them. Fortunately we have our choice of two other excellent date-time libraries: Joda-TimeThis popular open-source free-of-cost library can be used across several versions of Java. Many examples of its usage may be found on StackOverflow. Reading some of these will help get you up to speed quickly. java.time.* packageThis new set of classes are inspired by Joda-Time and defined by JSR 310. These classes are built into Java 8. A project is underway to backport these classes to Java 7, but that backporting is not backed by Oracle. As Kristopher Johnson correctly noted in his comment on the question, the other answers ignore vital issues of: Time of DayDate has both a date portion and a time-of-day portion) Time ZoneThe beginning of a day depends on the time zone. If you fail to specify a time zone, the JVM's default time zone is applied. That means the behavior of your code may change when run on other computers or with a modified time zone setting. Probably not what you want. LocaleThe Locale's language specifies how to interpret the words (name of month and of day) encountered during parsing. (The answer by BalusC handles this properly.) Also, the Locale affects the output of some formatters when generating a string representation of your date-time.
乔达时间
下面是关于Joda-Time的一些注意事项。
时区
在Joda-Time中,DateTime对象真正知道自己分配的时区。这与java.util.Date类形成对比,后者似乎有时区,但实际上没有。
请注意,在下面的示例代码中,我们如何将一个时区对象传递给解析字符串的格式化程序。该时区用于将日期-时间解释为发生在该时区。因此,您需要考虑并确定由字符串输入表示的时区。
由于您的输入字符串中没有时间部分,所以Joda-Time将指定时区的第一个时刻分配为一天的时间。通常这意味着00:00:00,但并不总是如此,因为日光节约时间(DST)或其他异常情况。顺便说一下,你可以通过调用withTimeAtStartOfDay对任何DateTime实例做同样的事情。
格式化程序模式
格式化程序模式中使用的字符在Joda-Time中类似于java.util中的字符。日期/日历,但不完全相同。仔细阅读诊断书。
不变性
我们通常在Joda-Time中使用不可变类。我们不会修改现有的Date-Time对象,而是调用基于其他对象创建新实例的方法,复制大多数方面(除非需要更改的地方除外)。下面最后一行中的withZone调用就是一个例子。不可变性有助于使Joda-Time非常线程安全,也可以使一些工作更加清晰。
转换
你将需要java.util.Date对象与其他不知道Joda-Time对象的类/框架一起使用。幸运的是,来回移动非常容易。
从java.util.Date对象(这里命名为date)到Joda-Time DateTime…
org.joda.time.DateTime dateTime = new DateTime( date, timeZone );
从Joda-Time到java.util.Date对象……
java.util.Date date = dateTime.toDate();
示例代码
String input = "January 2, 2010";
java.util.Locale locale = java.util.Locale.US;
DateTimeZone timeZone = DateTimeZone.forID( "Pacific/Honolulu" ); // Arbitrarily chosen for example.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "MMMM d, yyyy" ).withZone( timeZone ).withLocale( locale );
DateTime dateTime = formatter.parseDateTime( input );
System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTime in UTC/GMT: " + dateTime.withZone( DateTimeZone.UTC ) );
运行时……
dateTime: 2010-01-02T00:00:00.000-10:00
dateTime in UTC/GMT: 2010-01-02T10:00:00.000Z
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date;
try {
date = dateFormat.parse("2013-12-4");
System.out.println(date.toString()); // Wed Dec 04 00:00:00 CST 2013
String output = dateFormat.format(date);
System.out.println(output); // 2013-12-04
}
catch (ParseException e) {
e.printStackTrace();
}
这对我来说很有效。
我简陋的测试程序。我用它来摆弄格式化程序,查找我在日志文件中找到的长日期(但是谁把它们放在那里了……)
我的测试程序:
package be.test.package.time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
public class TimeWork {
public static void main(String[] args) {
TimeZone timezone = TimeZone.getTimeZone("UTC");
List<Long> longs = new ArrayList<>();
List<String> strings = new ArrayList<>();
//Formatting a date needs a timezone - otherwise the date get formatted to your system time zone.
//Use 24h format HH. In 12h format hh can be in range 0-11, which makes 12 overflow to 0.
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss.SSS");
formatter.setTimeZone(timezone);
Date now = new Date();
//Test dates
strings.add(formatter.format(now));
strings.add("01-01-1970 00:00:00.000");
strings.add("01-01-1970 00:00:01.000");
strings.add("01-01-1970 00:01:00.000");
strings.add("01-01-1970 01:00:00.000");
strings.add("01-01-1970 10:00:00.000");
strings.add("01-01-1970 12:00:00.000");
strings.add("01-01-1970 24:00:00.000");
strings.add("02-01-1970 00:00:00.000");
strings.add("01-01-1971 00:00:00.000");
strings.add("01-01-2014 00:00:00.000");
strings.add("31-12-1969 23:59:59.000");
strings.add("31-12-1969 23:59:00.000");
strings.add("31-12-1969 23:00:00.000");
//Test data
longs.add(now.getTime());
longs.add(-1L);
longs.add(0L); //Long date presentation at - midnight 1/1/1970 UTC - The timezone is important!
longs.add(1L);
longs.add(1000L);
longs.add(60000L);
longs.add(3600000L);
longs.add(36000000L);
longs.add(43200000L);
longs.add(86400000L);
longs.add(31536000000L);
longs.add(1388534400000L);
longs.add(7260000L);
longs.add(1417706084037L);
longs.add(-7260000L);
System.out.println("===== String to long =====");
//Show the long value of the date
for (String string: strings) {
try {
Date date = formatter.parse(string);
System.out.println("Formated date : " + string + " = Long = " + date.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
}
System.out.println("===== Long to String =====");
//Show the date behind the long
for (Long lo : longs) {
Date date = new Date(lo);
String string = formatter.format(date);
System.out.println("Formated date : " + string + " = Long = " + lo);
}
}
}
测试结果:
===== String to long =====
Formated date : 05-12-2014 10:17:34.873 = Long = 1417774654873
Formated date : 01-01-1970 00:00:00.000 = Long = 0
Formated date : 01-01-1970 00:00:01.000 = Long = 1000
Formated date : 01-01-1970 00:01:00.000 = Long = 60000
Formated date : 01-01-1970 01:00:00.000 = Long = 3600000
Formated date : 01-01-1970 10:00:00.000 = Long = 36000000
Formated date : 01-01-1970 12:00:00.000 = Long = 43200000
Formated date : 01-01-1970 24:00:00.000 = Long = 86400000
Formated date : 02-01-1970 00:00:00.000 = Long = 86400000
Formated date : 01-01-1971 00:00:00.000 = Long = 31536000000
Formated date : 01-01-2014 00:00:00.000 = Long = 1388534400000
Formated date : 31-12-1969 23:59:59.000 = Long = -1000
Formated date : 31-12-1969 23:59:00.000 = Long = -60000
Formated date : 31-12-1969 23:00:00.000 = Long = -3600000
===== Long to String =====
Formated date : 05-12-2014 10:17:34.873 = Long = 1417774654873
Formated date : 31-12-1969 23:59:59.999 = Long = -1
Formated date : 01-01-1970 00:00:00.000 = Long = 0
Formated date : 01-01-1970 00:00:00.001 = Long = 1
Formated date : 01-01-1970 00:00:01.000 = Long = 1000
Formated date : 01-01-1970 00:01:00.000 = Long = 60000
Formated date : 01-01-1970 01:00:00.000 = Long = 3600000
Formated date : 01-01-1970 10:00:00.000 = Long = 36000000
Formated date : 01-01-1970 12:00:00.000 = Long = 43200000
Formated date : 02-01-1970 00:00:00.000 = Long = 86400000
Formated date : 01-01-1971 00:00:00.000 = Long = 31536000000
Formated date : 01-01-2014 00:00:00.000 = Long = 1388534400000
Formated date : 01-01-1970 02:01:00.000 = Long = 7260000
Formated date : 04-12-2014 15:14:44.037 = Long = 1417706084037
Formated date : 31-12-1969 21:59:00.000 = Long = -7260000