Java string to date conversion
什么是最好的方式来转换一个EDCOX1×0的形式在"2010年1月2日"到一个EDCOX1,1,在Java?
最后,我要将月、日和年分解为整数,以便使用
1 2 3 4 5 |
将日期转换为时间。
这是最困难的方法,自从Java 1.1(1997)以来,EDCOX1的0个SET方法已经被弃用。只需使用与输入字符串匹配的格式模式,使用
在您的特定情况下,"2010年1月2日"作为输入字符串:
1 2 3 4 | String string ="January 2, 2010"; DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH); Date date = format.parse(string); System.out.println(date); // Sat Jan 02 00:00:00 GMT 2010 |
注意明确的
下面是JavaDoc的相关摘录,列出了所有可用的格式模式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | Letter Date or Time Component Presentation Examples ------ ---------------------- ------------------ ------------------------------------- G Era designator Text AD y Year Year 1996; 96 Y Week year Year 2009; 09 M/L 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 in week Text Tuesday; Tue u Day number of week 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 |
请注意,模式区分大小写,四个字符或更多字符的基于文本的模式表示完整的形式;否则,如果可用,将使用简短或缩写形式。因此,如
下面是一些有效的
1 2 3 4 5 6 7 8 9 10 11 12 13 | Input string Pattern ------------------------------------ ---------------------------- 2001.07.04 AD at 12:08:56 PDT yyyy.MM.dd G 'at' HH:mm:ss z Wed, Jul 4, '01 EEE, MMM d, ''yy 12:08 PM h:mm a 12 o'clock PM, Pacific Daylight Time hh 'o''clock' a, zzzz 0:08 PM, PDT K:mm a, z 02001.July.04 AD 12:08 PM yyyyy.MMMM.dd GGG hh:mm aaa Wed, 4 Jul 2001 12:08:56 -0700 EEE, d MMM yyyy HH:mm:ss Z 010704120856-0700 yyMMddHHmmssZ 2001-07-04T12:08:56.235-0700 yyyy-MM-dd'T'HH:mm:ss.SSSZ 2001-07-04T12:08:56.235-07:00 yyyy-MM-dd'T'HH:mm:ss.SSSXXX 2001-W27-3 YYYY-'W'ww-u |
一个重要的注意事项是
如果您恰巧是Java 8或更新的,那么使用EDCOX1 OR 10(这里,点击链接查看所有预定义的格式和可用的格式模式;教程在这里是可用的)。这个新的API的灵感来自于jodatime。
1 2 3 4 |
注意:如果您的格式模式恰好也包含时间部分,那么使用
下面是JavaDoc的相关摘录,列出了所有可用的格式模式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | Symbol Meaning Presentation Examples ------ -------------------------- ------------ ---------------------------------------------- G era text AD; Anno Domini; A u year year 2004; 04 y year-of-era year 2004; 04 D day-of-year number 189 M/L month-of-year number/text 7; 07; Jul; July; J d day-of-month number 10 Q/q quarter-of-year number/text 3; 03; Q3; 3rd quarter Y week-based-year year 1996; 96 w week-of-week-based-year number 27 W week-of-month number 4 E day-of-week text Tue; Tuesday; T e/c localized day-of-week number/text 2; 02; Tue; Tuesday; T F week-of-month number 3 a am-pm-of-day text PM h clock-hour-of-am-pm (1-12) number 12 K hour-of-am-pm (0-11) number 0 k clock-hour-of-am-pm (1-24) number 0 H hour-of-day (0-23) number 0 m minute-of-hour number 30 s second-of-minute number 55 S fraction-of-second fraction 978 A milli-of-day number 1234 n nano-of-second number 987654321 N nano-of-day number 1234000000 V time-zone ID zone-id America/Los_Angeles; Z; -08:30 z time-zone name zone-name Pacific Standard Time; PST O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00; X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15; x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15; Z zone-offset offset-Z +0000; -0800; -08:00; |
请注意,它有几个用于更流行模式的预定义格式化程序。因此,您可以使用
对于特定的输入字符串格式,您不需要使用显式的
是的,Java日期讨论,再次。为了处理日期操作,我们使用日期、日历、公历日历和simpledateformat。例如,使用您的一月日期作为输入:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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)); |
然后你可以用如下方法来操纵它:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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)); |
1 2 3 4 5 | String str_date ="11-June-07"; DateFormat formatter; Date date; formatter = new SimpleDateFormat("dd-MMM-yy"); date = formatter.parse(str_date); |
使用Java 8,我们得到了一个新的日期/时间API(JSR 310)。
下面的方法可以用来解析Java 8中的日期,而不依赖于JoDA时间:
1 |
1 2 3 | // if we 2nd even we have changed in pattern also it is not working please workout with 2nd DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM Q, yyyy", Locale.ENGLISH); LocalDate date = LocalDate.parse(str, formatter); |
1 2 3 4 5 | // access date fields int year = date.getYear(); // 2010 int day = date.getDayOfMonth(); // 2 Month month = date.getMonth(); // JANUARY int monthAsInt = month.getValue(); // 1 |
LoalalDead是用于表示日期(没有时间)的标准Java 8类。如果要分析包含日期和时间信息的值,则应使用localdatetime。对于带有时区的值,请使用ZonedDateTime。两者都提供了与
1 2 | LocalDateTime dateWithTime = LocalDateTime.parse(strWithDateAndTime, dateTimeFormatter); ZonedDateTime zoned = ZonedDateTime.parse(strWithTimeZone, zoneFormatter); |
datetimeformatter javadoc中的列表格式字符:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters. The following pattern letters are defined: Symbol Meaning Presentation Examples ------ ------- ------------ ------- G era text AD; Anno Domini; A u year year 2004; 04 y year-of-era year 2004; 04 D day-of-year number 189 M/L month-of-year number/text 7; 07; Jul; July; J d day-of-month number 10 Q/q quarter-of-year number/text 3; 03; Q3; 3rd quarter Y week-based-year year 1996; 96 w week-of-week-based-year number 27 W week-of-month number 4 E day-of-week text Tue; Tuesday; T e/c localized day-of-week number/text 2; 02; Tue; Tuesday; T F week-of-month number 3 a am-pm-of-day text PM h clock-hour-of-am-pm (1-12) number 12 K hour-of-am-pm (0-11) number 0 k clock-hour-of-am-pm (1-24) number 0 H hour-of-day (0-23) number 0 m minute-of-hour number 30 s second-of-minute number 55 S fraction-of-second fraction 978 A milli-of-day number 1234 n nano-of-second number 987654321 N nano-of-day number 1234000000 V time-zone ID zone-id America/Los_Angeles; Z; -08:30 z time-zone name zone-name Pacific Standard Time; PST O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00; X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15; x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15; Z zone-offset offset-Z +0000; -0800; -08:00; |
虽然有些答案在技术上是正确的,但并不可取。
- java.util.date&calendar类是出了名的麻烦事。由于设计和实现上的缺陷,请避免它们。幸运的是,我们还可以选择其他两个优秀的日期时间库:
- JoDayTimes这个流行的开源免费的库可以跨几个版本的Java使用。在stackoverflow中可以找到许多使用它的示例。阅读其中的一些内容将有助于你快速掌握速度。
- Java.Time.*P包装这个新的类集合是由JoDA时间启发的,由JSR 310定义。这些类内置到Java 8中。正在进行一个项目,将这些类备份到Java 7,但后退不是由Oracle支持的。
- 正如克里斯托弗·约翰逊在他对这个问题的评论中正确指出的那样,其他答案忽略了以下重要问题:
- 日期时间既有日期部分,也有日期时间部分)
- 时区一天的开始取决于时区。如果未能指定时区,则应用JVM的默认时区。这意味着在其他计算机上运行或使用修改的时区设置时,代码的行为可能会更改。可能不是你想要的。
- locale the locale的语言指定如何解释解析过程中遇到的单词(月份和日期的名称)。(Balusc的答案处理得很好。)此外,当生成日期时间的字符串表示形式时,区域设置会影响某些格式化程序的输出。
乔达时间
接下来是一些关于佐达时间的笔记。
时区在Joda Time中,日期时间对象真正知道自己分配的时区。这与java.util.date类形成了对比,后者似乎有时区,但没有时区。
请注意下面的示例代码中,我们如何将时区对象传递给解析字符串的格式化程序。该时区用于将该日期时间解释为发生在该时区中。因此,您需要考虑并确定由该字符串输入表示的时区。
由于输入字符串中没有时间部分,所以joda time将指定时区中一天中的第一个时间指定为一天中的时间。通常这意味着
格式化程序模式中使用的字符在joda time中与java.util.date/calendar中的字符相似,但并不完全相同。仔细阅读文件。
不变性我们通常在joda time中使用不可变类。我们不修改现有的日期时间对象,而是调用基于其他对象创建新的新实例的方法,这些新实例的大部分方面都已复制,但需要修改的地方除外。例如下面最后一行中对
您将需要java.util.date对象与不了解Joda时间对象的其他类/框架一起使用。幸运的是,它很容易来回移动。
从java.util.date对象(此处名为
1 | org.joda.time.DateTime dateTime = new DateTime( date, timeZone ); |
从joda time转到java.util.date对象…
1 |
样例代码
1 2 3 4 5 6 7 8 9 | 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 ) ); |
跑步时…
1 2 | dateTime: 2010-01-02T00:00:00.000-10:00 dateTime in UTC/GMT: 2010-01-02T10:00:00.000Z |
在处理simpledateformat类时,必须记住日期不是线程安全的,并且不能与多个线程共享单个日期对象。
"M"和"M"也有很大的区别,其中小箱子用分钟,大写箱子用月。与"d"和"d"相同。这会导致经常被忽视的细微缺陷。更多细节请参阅JavaDoc或Java中转换字符串的指南。
1 2 3 4 5 6 7 8 9 10 11 12 | 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(); } |
对我来说很好。
此外,SimpleDateFormat不适用于某些客户端技术,如GWT。
最好选择calendar.getInstance(),您的要求是比较两个日期;选择长日期。
可以使用simpledateformat将字符串更改为日期
1 2 3 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String strDate ="2000-01-01"; Date date = new Date(sdf.parse(strDate).getTime()); |
我们使用的两个简单格式化程序:
我们分析完整的日期到时间格式:
1 2 3 4 5 6 7 8 9 10 11 | date="2016-05-06 16:40:32"; public static String setDateParsing(String date) throws ParseException { // This is the format date we want DateFormat mSDF = new SimpleDateFormat("hh:mm a"); // This format date is actually present SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd hh:mm"); return mSDF.format(formatter.parse(date)); } |
我简陋的测试程序。我用它来和格式化程序一起玩,查找我在日志文件中找到的长日期(但是谁把它们放在那里…)。
我的测试程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | 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); } } } |
试验结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | ===== 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 |
源链接
对于Android
calendar.getInstance().getTime()给出
1 | Thu Jul 26 15:54:13 GMT+05:30 2018 |
使用
1 2 3 | String oldDate ="Thu Jul 26 15:54:13 GMT+05:30 2018"; DateFormat format = new SimpleDateFormat("EEE LLL dd HH:mm:ss Z yyyy"); Date updateLast = format.parse(oldDate); |
试试这个
1 2 3 | String date = get_pump_data.getString("bond_end_date"); DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); Date datee = (Date)format.parse(date); |