java.util.Date格式转换yyyy-mm-dd到mm-dd-yyyy

时间:2013-08-28 06:16:58

标签: java date date-format

我的java.util.Date格式为yyyy-mm-dd。我希望它的格式为mm-dd-yyyy

以下是我尝试进行此转换的示例工具:

// Setting the pattern
    SimpleDateFormat sm = new SimpleDateFormat("mm-dd-yyyy");
    // myDate is the java.util.Date in yyyy-mm-dd format
    // Converting it into String using formatter
    String strDate = sm.format(myDate);
    //Converting the String back to java.util.Date
    Date dt = sm.parse(strDate);

我得到的输出仍然不是mm-dd-yyyy格式。

请告诉我如何将java.util.Date格式从yyyy-mm-dd格式化为mm-dd-yyyy

8 个答案:

答案 0 :(得分:129)

Date是自Unix时代(1970年1月1日00:00:00 UTC)以来毫秒数的容器。

它没有格式概念。

Java 8 +

LocalDateTime ldt = LocalDateTime.now();
System.out.println(DateTimeFormatter.ofPattern("MM-dd-yyyy", Locale.ENGLISH).format(ldt));
System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH).format(ldt));
System.out.println(ldt);

...输出

05-11-2018
2018-05-11
2018-05-11T17:24:42.980

Java 7 -

您应该使用ThreeTen Backport

原始答案

例如......

Date myDate = new Date();
System.out.println(myDate);
System.out.println(new SimpleDateFormat("MM-dd-yyyy").format(myDate));
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(myDate));
System.out.println(myDate);

...输出

Wed Aug 28 16:20:39 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 16:20:39 EST 2013

没有格式化更改了基础Date值。这是DateFormatter s

的目的

更新了其他示例

以防万一第一个例子没有意义......

此示例使用两个格式化程序格式化同一日期。然后,我使用这些相同的格式化程序将String值解析回Date。生成的解析不会改变Date报告其值的方式。

Date#toString只是它内容的转储。您无法更改此设置,但您可以按照自己喜欢的方式格式化Date对象

try {
    Date myDate = new Date();
    System.out.println(myDate);

    SimpleDateFormat mdyFormat = new SimpleDateFormat("MM-dd-yyyy");
    SimpleDateFormat dmyFormat = new SimpleDateFormat("yyyy-MM-dd");

    // Format the date to Strings
    String mdy = mdyFormat.format(myDate);
    String dmy = dmyFormat.format(myDate);

    // Results...
    System.out.println(mdy);
    System.out.println(dmy);
    // Parse the Strings back to dates
    // Note, the formats don't "stick" with the Date value
    System.out.println(mdyFormat.parse(mdy));
    System.out.println(dmyFormat.parse(dmy));
} catch (ParseException exp) {
    exp.printStackTrace();
}

哪些输出......

Wed Aug 28 16:24:54 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 00:00:00 EST 2013
Wed Aug 28 00:00:00 EST 2013

另外,请注意格式模式。仔细查看SimpleDateFormat以确保您没有使用错误的模式;)

答案 1 :(得分:31)

SimpleDateFormat("MM-dd-yyyy");

而不是

SimpleDateFormat("mm-dd-yyyy");

因为MM points Monthmm points minutes

SimpleDateFormat sm = new SimpleDateFormat("MM-dd-yyyy");
String strDate = sm.format(myDate);

答案 2 :(得分:14)

'M'(资本)代表月份& 'm'(简单)代表分钟

几个月的例子

'M' -> 7  (without prefix 0 if it is single digit)
'M' -> 12

'MM' -> 07 (with prefix 0 if it is single digit)
'MM' -> 12

'MMM' -> Jul (display with 3 character)

'MMMM' -> December (display with full name)

分钟的一些例子

'm' -> 3  (without prefix 0 if it is single digit)
'm' -> 19
'mm' -> 03 (with prefix 0 if it is single digit)
'mm' -> 19

答案 3 :(得分:3)

TL;博士

LocalDate.parse( 
    "01-23-2017" , 
    DateTimeFormatter.ofPattern( "MM-dd-uuuu" )
)

详细

  

我有一个格式为yyyy-mm-dd

的java.util.Date

正如其他提到的,Date类没有格式。自UTC 1970年以来,它具有毫秒数。没有附加条件。

java.time

其他Answers使用麻烦的旧遗留日期时间类,现在由java.time类取代。

如果您有java.util.Date,请转换为Instant对象。 Instant类代表UTC中时间轴上的一个时刻,分辨率为nanoseconds(小数部分最多九(9)位)。

Instant instant = myUtilDate.toInstant();

时区

其他答案忽略了时区的关键问题。确定日期需要时区。对于任何给定的时刻,日期在全球范围内因地区而异。巴黎午夜过后几分钟法国是一个新的一天,而在魁北克蒙特利尔仍然是“昨天”。

定义您希望Instant的上下文所用的时区。

ZoneId z = ZoneId.of( "America/Montreal" );

应用ZoneId获取ZonedDateTime

ZonedDateTime zdt = instant.atZone( z );

LocalDate

如果您只关心没有时间的日期,请提取LocalDate

LocalDate localDate = zdt.toLocalDate();

要生成标准ISO 8601格式的字符串YYYY-MM-DD,只需调用toString即可。生成/解析字符串时,java.time类默认使用标准格式。

String output = localDate.toString();
  

2017年1月23日

如果您想要MM-DD-YYYY格式,请定义格式化模式。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" );
String output = localDate.format( f );

请注意,格式设置模式代码区分大小写。问题中的代码错误地使用了mm(分钟)而不是MM(一年中的某个月)。

使用相同的DateTimeFormatter对象进行解析。 java.time类是线程安全的,因此您可以保留此对象并重复使用它甚至跨线程。

LocalDate localDate = LocalDate.parse( "01-23-2017" , f );

关于java.time

java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendar和& SimpleDateFormat

现在位于Joda-Timemaintenance mode项目建议迁移到java.time类。

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

从哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如IntervalYearWeekYearQuartermore

答案 4 :(得分:1)

下面的代码很简单。

import sqlite3

conn = sqlite3.connect('mydb.sqlite')
cur = conn.cursor()

cur.execute('''
DROP TABLE IF EXISTS Counts''')

cur.execute('''CREATE TABLE Counts (org TEXT, count INTEGER)''')

fname = raw_input('Enter file name: ')
if ( len(fname) < 1 ) : fname = 'abc.txt'
fh = open(fname)
for line in fh:
    if not (line.startswith('From: ')) : continue
    pieces = line.split()
    org = pieces[1].split('@')[1]
    print org
    cur.execute('''SELECT count FROM Counts WHERE org = ? ''', (org, ))
    row = cur.fetchone()
    if row is None:
        cur.execute('''INSERT INTO Counts (org, count) VALUES ( ?, 1 )''', ( org, ) )
    else : 
        cur.execute('''UPDATE Counts SET count=count+1 WHERE org = ?''', 
        (org, ))
# This statement commits outstanding changes to disk each 
# time through the loop - the program can be made faster 
# by moving the commit so it runs only after the loop completes
conn.commit()


sqlstr = '''SELECT org, count FROM Counts ORDER BY count DESC LIMIT 10'''

print "Counts:"
for row in cur.execute(sqlstr) :
    print str(row[0]), row[1]

cur.close()

答案 5 :(得分:1)

您可以获取日,月和年,并可以将它们连接起来,或者可以使用MM-dd-yyyy格式,如下所示。

Date date1 = new Date();
String mmddyyyy1 = new SimpleDateFormat("MM-dd-yyyy").format(date1);
System.out.println("Formatted Date 1: " + mmddyyyy1);



Date date2 = new Date();
Calendar calendar1 = new GregorianCalendar();
calendar1.setTime(date2);
int day1   = calendar1.get(Calendar.DAY_OF_MONTH);
int month1 = calendar1.get(Calendar.MONTH) + 1; // {0 - 11}
int year1  = calendar1.get(Calendar.YEAR);
String mmddyyyy2 = ((month1<10)?"0"+month1:month1) + "-" + ((day1<10)?"0"+day1:day1) + "-" + (year1);
System.out.println("Formatted Date 2: " + mmddyyyy2);



LocalDateTime ldt1 = LocalDateTime.now();  
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("MM-dd-yyyy");  
String mmddyyyy3 = ldt1.format(format1);  
System.out.println("Formatted Date 3: " + mmddyyyy3);  



LocalDateTime ldt2 = LocalDateTime.now();
int day2 = ldt2.getDayOfMonth();
int mont2= ldt2.getMonthValue();
int year2= ldt2.getYear();
String mmddyyyy4 = ((mont2<10)?"0"+mont2:mont2) + "-" + ((day2<10)?"0"+day2:day2) + "-" + (year2);
System.out.println("Formatted Date 4: " + mmddyyyy4);



LocalDateTime ldt3 = LocalDateTime.of(2020, 6, 11, 14, 30); // int year, int month, int dayOfMonth, int hour, int minute
DateTimeFormatter format2 = DateTimeFormatter.ofPattern("MM-dd-yyyy");  
String mmddyyyy5 = ldt3.format(format2);   
System.out.println("Formatted Date 5: " + mmddyyyy5); 



Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(new Date());
int day3  = calendar2.get(Calendar.DAY_OF_MONTH); // OR Calendar.DATE
int month3= calendar2.get(Calendar.MONTH) + 1;
int year3 = calendar2.get(Calendar.YEAR);
String mmddyyyy6 = ((month3<10)?"0"+month3:month3) + "-" + ((day3<10)?"0"+day3:day3) + "-" + (year3);
System.out.println("Formatted Date 6: " + mmddyyyy6);



Date date3 = new Date();
LocalDate ld1 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date3)); // Accepts only yyyy-MM-dd
int day4  = ld1.getDayOfMonth();
int month4= ld1.getMonthValue();
int year4 = ld1.getYear();
String mmddyyyy7 = ((month4<10)?"0"+month4:month4) + "-" + ((day4<10)?"0"+day4:day4) + "-" + (year4);
System.out.println("Formatted Date 7: " + mmddyyyy7);



Date date4 = new Date();
int day5   = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getDayOfMonth();
int month5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getMonthValue();
int year5  = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getYear();
String mmddyyyy8 = ((month5<10)?"0"+month5:month5) + "-" + ((day5<10)?"0"+day5:day5) + "-" + (year5);
System.out.println("Formatted Date 8: " + mmddyyyy8);



Date date5 = new Date();
int day6   = Integer.parseInt(new SimpleDateFormat("dd").format(date5));
int month6 = Integer.parseInt(new SimpleDateFormat("MM").format(date5));
int year6  = Integer.parseInt(new SimpleDateFormat("yyyy").format(date5));
String mmddyyyy9 = ((month6<10)?"0"+month6:month6) + "-" + ((day6<10)?"0"+day6:day6) + "-" + (year6);`enter code here`
System.out.println("Formatted Date 9: " + mmddyyyy9);

答案 6 :(得分:0)

请将小“mm”月更改为大写“MM”,它将起作用。以下参考示例代码。

  **Date myDate = new Date();
    SimpleDateFormat sm = new SimpleDateFormat("MM-dd-yyyy");

    String strDate = sm.format(myDate);

    Date dt = sm.parse(strDate);
    System.out.println(strDate);**

答案 7 :(得分:0)

请参阅这些。

格式化日期

DateTimeFormatter

解析日期

Instant with zone

相关问题