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

514

我有一个表示日期的 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。我做错了什么?


182
"yyyyy不同于yyyy。:)" - Hovercraft Full Of Eels
2
一个回旋镖式的问题。你的使用场景是什么?因为有可能你应该使用内置模式(DateFormat.getDateTimeInstance())。 - Paweł Dyda
13
格式字符串中表示月份的是MM,而不是像上面的例子中所示的mm,mm代表分钟。 - Mike
3
我将yyyy-mm-dd更改为yyyy-MM-dd,因为初始版本无法运行。 - Pavlo Zvarych
2
"mm"是分钟数 :) - Fuad Efendi
"yyyyy-MM-dd hh:mm:ss": - Guilherme
23个回答

7
public class SystemDateTest {

    String stringDate;

    public static void main(String[] args) {
        SystemDateTest systemDateTest = new SystemDateTest();
        // format date into String
        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;
    }
}

3
请在您的答案中添加一些信息来解释您的代码。 - Kursad Gulseven
有一个名为getDate()的方法,通过它可以获取日期对象,然后应用SimpleDateFormat,以便根据SimpleDateFormat构造函数中定义的格式将日期转换,然后在StringDate方法中设置。您可以将其缓存。 - Neeraj Gahlawat

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));

6

您可以尝试使用Java 8的新date功能,更多信息可在Oracle文档中找到。

或者您可以尝试使用旧版。

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);
}

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);

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);
};

4

将提供的格式中的一个y删除:

SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");

希望如下:

SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");

不完全正确。你还需要正确的大小写(无论你使用现代的DateTimeFormatter还是坚持使用过时的SimpleDateFormat)。 - Ole V.V.

1
/**
 * 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;
}

1
我们可以将今天的日期转换为'JUN 12, 2020'格式。
String.valueOf(DateFormat.getDateInstance().format(new Date())));

0

java.time

在2014年3月,现代日期时间API* API替换了容易出错的java.util日期时间API以及它们的格式化API SimpleDateFormat。自那时起,强烈建议停止使用旧API。
另外,下面引用的是Joda-Time首页上的通知:

请注意,从Java SE 8开始,用户被要求迁移到java.time(JSR-310) - JDK的核心部分,取代这个项目。

您不需要DateTimeFormatter进行格式化

你只需要使用DateTimeFormatter来解析字符串,但是你不需要使用DateTimeFormatter来获得特定格式的日期。现代化的时间日期API基于ISO 8601标准,因此java.time类型的toString实现返回ISO 8601格式的字符串。而你所需的格式是LocalDate#toString的默认格式。

使用现代化的时间日期API java.time的解决方案:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String strDate = "2011-01-18 00:00:00.0";
        DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d H:m:s.S", Locale.ENGLISH);
        LocalDateTime ldt = LocalDateTime.parse(strDate, dtfInput);
        // Alternatively,
        // LocalDateTime ldt = dtfInput.parse(strDate, LocalDateTime::from);

        LocalDate date = ldt.toLocalDate();
        System.out.println(date);
    }
}

输出:

2011-01-18

在线演示

关于解决方案的一些重要说明:

  1. java.time 使得在日期时间类型本身上调用parseformat函数成为可能,除了传统的方式(即在格式化程序类型上调用parseformat函数,在java.time API的情况下是DateTimeFormatter)。
  2. 在这里,您可以使用y代替u,但是我更喜欢u而不是y

Trail:日期时间了解更多关于现代日期时间API的信息。


* 如果由于任何原因您不得不坚持使用Java 6或Java 7,那么您可以使用ThreeTen-Backport,它将大部分java.time功能反向移植到Java 6和7。如果您正在为Android项目工作,而您的Android API级别仍不符合Java-8,请检查通过desugaring可用的Java 8+ APIs以及如何在Android项目中使用ThreeTenABP


0

你有一些错误:

第一点:

应该是

new SimpleDateFormat("yyyy-mm-dd");

// yyyy 是4位数,不是5位数

这会显示02011,但是yyyy会显示2011。

第二点:

将你的代码更改为以下内容:

new SimpleDateFormat("yyyy-MM-dd");

希望能帮到你。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接