我有一个表示日期的字符串。

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

我想把它转换成一个日期,并以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。我做错了什么?


当前回答

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

其他回答

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

java.time

2014年3月,现代日期时间API* API取代了容易出错的java。SimpleDateFormat. util日期时间API和它们的格式化API。从那时起,强烈建议停止使用遗留API。

此外,下面引用的是Joda-Time主页的通知:

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

格式化不需要DateTimeFormatter

您只需要DateTimeFormatter来解析字符串,但不需要DateTimeFormatter来获得所需格式的日期。现代Date-Time API基于ISO 8601,因此是java的toString实现。时间类型返回ISO 8601格式的字符串。您想要的格式是localdate# toString的默认格式。

使用java解决方案。time,现代Date-Time API:

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

在线演示

关于解决方案的一些重要注意事项:

java。time使得在Date-Time类型本身上调用解析和格式化函数成为可能,除了传统的方式(即在formatter类型上调用解析和格式化函数,在java中是DateTimeFormatter。时间API)。 这里,你可以用y代替u但我更喜欢u而不是y。

从Trail: Date Time了解更多关于现代Date-Time API的信息。


*无论出于何种原因,如果你必须坚持使用Java 6或Java 7,你可以使用ThreeTen-Backport,它可以向后移植大部分Java。Java 6和7的时间功能。如果你正在为一个Android项目工作,你的Android API级别仍然不兼容Java-8,检查Java 8+ API通过desugaring和如何使用ThreeTenABP在Android项目。

我们可以将今天的日期转换为“2020年6月12日”的格式。

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

使用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 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()将日期格式化为特定模式的字符串。

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

参见:

Java字符串到日期的转换


更新:根据你的失败的尝试,你添加到这个问题后的答案张贴;模式是区分大小写的。仔细阅读java.text.SimpleDateFormat javadoc中各个部分代表什么。举个例子,M代表月,M代表分钟。此外,年份是四位数yyyy,而不是五位数yyyyy。仔细看看我上面发布的代码片段。

假设您想将2019-12-20 10:50 AM GMT+6:00更改为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;
}

这个函数将返回您想要的答案。如果你想自定义更多,只需从日期格式中添加或删除组件。