更改Java字符串中的日期格式

时间:2011-01-23 05:09:48

标签: java string date formatting date-format

我有String代表约会。

String date_s = "2011-01-18 00:00:00.0";

我想将其转换为Date并以YYYY-MM-DD格式输出。

  

2011-01-18

我怎样才能做到这一点?


好的,根据我在下面找到的答案,这是我尝试过的东西:

String date_s = " 2011-01-18 00:00:00.0"; 
SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss"); 
Date date = dt.parse(date_s); 
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
System.out.println(dt1.format(date));

但它会输出02011-00-1而不是所需的2011-01-18。我做错了什么?

21 个答案:

答案 0 :(得分:487)

使用LocalDateTime#parse()(如果字符串恰好包含时区部分,则为ZonedDateTime#parse())以某种模式将String解析为LocalDateTime

String oldstring = "2011-01-18 00:00:00.0";
LocalDateTime datetime = LocalDateTime.parse(oldstring, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));

使用LocalDateTime#format()(或ZonedDateTime#format())以特定模式将LocalDateTime格式化为String

String newstring = datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(newstring); // 2011-01-18

,当您还没有使用Java 8时,请使用SimpleDateFormat#parse()将某个模式中的String解析为Date

String oldstring = "2011-01-18 00:00:00.0";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(oldstring);

使用SimpleDateFormat#format()以特定模式将Date格式化为String

String newstring = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(newstring); // 2011-01-18

另见:


更新:根据您的失败尝试:模式区分大小写。阅读java.text.SimpleDateFormat javadoc各个部分代表的内容。例如代表M几个月,m代表分钟。此外,存在四位数yyyy而不是五位yyyyy的年份。仔细看看我在上面发布的代码片段。

答案 1 :(得分:147)

格式是CASE-SENSITIVE因此使用MM的月份不是mm(这是分钟)和yyyy 对于Reference,您可以使用以下备忘单。

G   Era designator  Text    AD
y   Year    Year    1996; 96
Y   Week year   Year    2009; 09
M   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 name in week    Text    Tuesday; Tue
u   Day number of week (1 = Monday, ..., 7 = Sunday)    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

示例:

"yyyy.MM.dd G 'at' HH:mm:ss z"  2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy"  Wed, Jul 4, '01
"h:mm a"    12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa"  02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z"    Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"   2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"   2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u"  2001-W27-3

答案 2 :(得分:105)

答案当然是创建一个SimpleDateFormat对象并使用它来解析字符串到日期并将日期格式化为字符串。如果您尝试使用SimpleDateFormat并且无效,请显示您的代码以及您可能收到的任何错误。

附录:格式为String的“mm”与“MM”不同。使用MM数月,mm使用数分钟。而且,yyyyy与yyyy不同。 。e.g,:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FormateDate {

    public static void main(String[] args) throws ParseException {
        String date_s = "2011-01-18 00:00:00.0";

        // *** note that it's "yyyy-MM-dd hh:mm:ss" not "yyyy-mm-dd hh:mm:ss"  
        SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = dt.parse(date_s);

        // *** same for the format String below
        SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(dt1.format(date));
    }

}

答案 3 :(得分:21)

为什么不简单地使用这个

Date convertToDate(String receivedDate) throws ParseException{
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
        Date date = formatter.parse(receivedDate);
        return date;
    }

另外,这是另一种方式:

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String requiredDate = df.format(new Date()).toString();

Date requiredDate = df.format(new Date());

干杯!

答案 4 :(得分:15)

在Java 8及更高版本中使用java.time包:

String date = "2011-01-18 00:00:00.0";
TemporalAccessor temporal = DateTimeFormatter
    .ofPattern("yyyy-MM-dd HH:mm:ss.S")
    .parse(date); // use parse(date, LocalDateTime::from) to get LocalDateTime
String output = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(temporal);

答案 5 :(得分:9)

[编辑包含BalusC的更正] SimpleDateFormat类应该可以解决问题:

String pattern = "yyyy-MM-dd HH:mm:ss.S";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
  Date date = format.parse("2011-01-18 00:00:00.0");
  System.out.println(date);
} catch (ParseException e) {
  e.printStackTrace();
}

答案 6 :(得分:9)

请在此处参阅“日期和时间模式”。 http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;

public class DateConversionExample{

  public static void main(String arg[]){

    try{

    SimpleDateFormat sourceDateFormat = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");

    Date date = sourceDateFormat.parse("2011-01-18 00:00:00.0");


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

    }catch(ParseException e){
        e.printStackTrace();
    }
  } 

}

答案 7 :(得分:9)

其他答案都是正确的,基本上你的模式中“y”字符的数量是错误的。

时区

但是还有一个问题......你没有解决时区问题。如果您打算UTC,那么您应该这样说。如果没有,答案就不完整了。如果您想要的只是没有时间的日期部分,那么没有问题。但如果你做了可能涉及时间的进一步工作,那么你应该指定一个时区。

约达时间

以下是使用第三方开源Joda-Time 2.3库的相同类型的代码

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.

String date_s = "2011-01-18 00:00:00.0";

org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern( "yyyy-MM-dd' 'HH:mm:ss.SSS" );
// By the way, if your date-time string conformed strictly to ISO 8601 including a 'T' rather than a SPACE ' ', you could
// use a formatter built into Joda-Time rather than specify your own: ISODateTimeFormat.dateHourMinuteSecondFraction().
// Like this:
//org.joda.time.DateTime dateTimeInUTC = org.joda.time.format.ISODateTimeFormat.dateHourMinuteSecondFraction().withZoneUTC().parseDateTime( date_s );

// Assuming the date-time string was meant to be in UTC (no time zone offset).
org.joda.time.DateTime dateTimeInUTC = formatter.withZoneUTC().parseDateTime( date_s );
System.out.println( "dateTimeInUTC: " + dateTimeInUTC );
System.out.println( "dateTimeInUTC (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInUTC ) );
System.out.println( "" ); // blank line.

// Assuming the date-time string was meant to be in Kolkata time zone (formerly known as Calcutta). Offset is +5:30 from UTC (note the half-hour).
org.joda.time.DateTimeZone kolkataTimeZone = org.joda.time.DateTimeZone.forID( "Asia/Kolkata" );
org.joda.time.DateTime dateTimeInKolkata = formatter.withZone( kolkataTimeZone ).parseDateTime( date_s );
System.out.println( "dateTimeInKolkata: " + dateTimeInKolkata );
System.out.println( "dateTimeInKolkata (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInKolkata ) );
// This date-time in Kolkata is a different point in the time line of the Universe than the dateTimeInUTC instance created above. The date is even different.
System.out.println( "dateTimeInKolkata adjusted to UTC: " + dateTimeInKolkata.toDateTime( org.joda.time.DateTimeZone.UTC ) );

跑步时......

dateTimeInUTC: 2011-01-18T00:00:00.000Z
dateTimeInUTC (date only): 2011-01-18

dateTimeInKolkata: 2011-01-18T00:00:00.000+05:30
dateTimeInKolkata (date only): 2011-01-18
dateTimeInKolkata adjusted to UTC: 2011-01-17T18:30:00.000Z

答案 8 :(得分:8)

try
 {
    String date_s = "2011-01-18 00:00:00.0";
    SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
    Date tempDate=simpledateformat.parse(date_s);
    SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd");           
    System.out.println("Output date is = "+outputDateFormat.format(tempDate));
  } catch (ParseException ex) 
  {
        System.out.println("Parse Exception");
  }

答案 9 :(得分:7)

public class SystemDateTest {

    String stringDate;

    public static void main(String[] args) {
        SystemDateTest systemDateTest = new SystemDateTest();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
        systemDateTest.setStringDate(simpleDateFormat.format(systemDateTest.getDate()));
        System.out.println(systemDateTest.getStringDate());
    }

    public Date getDate() {
        return new Date();
    }

    public String getStringDate() {
        return stringDate;
    }

    public void setStringDate(String stringDate) {
        this.stringDate = stringDate;
    }
}

答案 10 :(得分:6)

   String str = "2000-12-12";
   Date dt = null;
   SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

    try 
    {
         dt = formatter.parse(str);
    }
    catch (Exception e)
    {
    }

    JOptionPane.showMessageDialog(null, formatter.format(dt));

答案 11 :(得分:5)

您也可以使用substring()

String date_s = "2011-01-18 00:00:00.0";
date_s.substring(0,10);

如果您想在日期前面留出空格,请使用

String date_s = " 2011-01-18 00:00:00.0";
date_s.substring(1,11);

答案 12 :(得分:5)

你可以使用:

Date yourDate = new Date();

SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
String date = DATE_FORMAT.format(yourDate);

完美无缺!

答案 13 :(得分:4)

private SimpleDateFormat dataFormat = new SimpleDateFormat("dd/MM/yyyy");

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    if(value instanceof Date) {
        value = dataFormat.format(value);
    }
    return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
};

答案 14 :(得分:3)

删除一个y表单SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");应为SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");

答案 15 :(得分:3)

您可以尝试使用java 8 new date,可以在oracle documentation上找到更多信息。

或者你可以尝试旧的

public static Date getDateFromString(String format, String dateStr) {

        DateFormat formatter = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = (Date) formatter.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return date;
    }

    public static String getDate(Date date, String dateFormat) {
        DateFormat formatter = new SimpleDateFormat(dateFormat);
        return formatter.format(date);
    }

答案 16 :(得分:0)

说您想将格林威治标准时间2019-12-20 10:50更改为2019-12-20 10:50 AM 首先,您必须了解日期格式。第一个日期格式是 yyyy-MM-dd hh:mm a zzz和第二个日期格式将是yyyy-MM-dd hh:mm a

只需从此函数返回一个字符串即可。

public String convertToOnlyDate(String currentDate) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a ");
    Date date;
    String dateString = "";
    try {
        date = dateFormat.parse(currentDate);
        System.out.println(date.toString()); 

        dateString = dateFormat.format(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return dateString;
}

此功能将返回您想要的答案。如果要自定义更多内容,只需在日期格式中添加或删除组件。

答案 17 :(得分:0)

我们可以将日期转换为'2020年6月12日'

String.valueOf(DateFormat.getDateInstance().format(new Date())));

答案 18 :(得分:0)

你错了: SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");

首先: 应该 new SimpleDateFormat("yyyy-mm-dd"); //yyyy 4 不是 5 此显示为 02011,但 yyyy 显示为 2011

第二: 像这样改变你的代码 new SimpleDateFormat("yyyy-MM-dd");

希望能帮到你

答案 19 :(得分:0)

/**
 * Method will take Date in "MMMM, dd yyyy HH:mm:s" format and return time difference like added: 3 min ago
 *
 * @param date : date in "MMMM, dd yyyy HH:mm:s" format
 * @return : time difference
 */
private String getDurationTimeStamp(String date) {
    String timeDifference = "";

    //date formatter as per the coder need
    SimpleDateFormat sdf = new SimpleDateFormat("MMMM, dd yyyy HH:mm:s");
    TimeZone timeZone = TimeZone.getTimeZone("EST");
    sdf.setTimeZone(timeZone);
    Date startDate = null;
    try {
        startDate = sdf.parse(date);
    } catch (ParseException e) {
        MyLog.printStack(e);
    }

    //end date will be the current system time to calculate the lapse time difference
    Date endDate = new Date();

    //get the time difference in milliseconds
    long duration = endDate.getTime() - startDate.getTime();

    long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
    long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
    long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
    long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);

    if (diffInDays >= 365) {
        int year = (int) (diffInDays / 365);
        timeDifference = year + mContext.getString(R.string.year_ago);
    } else if (diffInDays >= 30) {
        int month = (int) (diffInDays / 30);
        timeDifference = month + mContext.getString(R.string.month_ago);
    }
    //if days are not enough to create year then get the days
    else if (diffInDays >= 1) {
        timeDifference = diffInDays + mContext.getString(R.string.day_ago);
    }
    //if days value<1 then get the hours
    else if (diffInHours >= 1) {
        timeDifference = diffInHours + mContext.getString(R.string.hour_ago);
    }
    //if hours value<1 then get the minutes
    else if (diffInMinutes >= 1) {
        timeDifference = diffInMinutes + mContext.getString(R.string.min_ago);
    }
    //if minutes value<1 then get the seconds
    else if (diffInSeconds >= 1) {
        timeDifference = diffInSeconds + mContext.getString(R.string.sec_ago);
    } else if (timeDifference.isEmpty()) {
        timeDifference = mContext.getString(R.string.now);
    }

    return mContext.getString(R.string.added) + " " + timeDifference;
}

答案 20 :(得分:-1)

SimpleDateFormat dt1 =新的SimpleDateFormat(“ yyyy-mm-dd”);