简体   繁体   English

如何从字符串日期更改日期格式

[英]how to change format of date from string date

I have date as a string like this 我有这样的日期作为字符串

String date = "11-12-2018"

I want to change it to "2018-12-11" 我想将其更改为“ 2018-12-11”

with the same variable. 具有相同的变量。 So, I tried the code below but it doesn't give me the output I expect. 因此,我尝试了下面的代码,但没有得到预期的输出。

String date = "11-12-2018"

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

Date d = df.parse(date);

results in: "0012-06-09" 结果为:“ 0012-06-09”


I want "2018-12-11" 我想要“ 2018-12-11”

You can do this 3 ways. 您可以通过3种方式执行此操作。 First is using SimpleDateFormat and Date and second using DateTimeFormatter and LocalDate and third you can use Split . 第一种是使用SimpleDateFormatDate ,第二种是使用DateTimeFormatterLocalDate ,第三种是可以使用Split

1. Using Date and SimpleDateFormat 1.使用Date和SimpleDateFormat

String date = "11-12-2018";
SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
java.util.Date d = df.parse(date);
String finalDate = new SimpleDateFormat("yyyy-MM-dd").format(d);
System.out.println(finalDate);

Here we have our actual date String date = "11-12-2018"; 这里我们有实际的日期String date = "11-12-2018"; we know we want to change it to 2018-12-11 我们知道我们想将其更改为2018-12-11

So lets parse that date into a Date object using this code 因此,让我们使用此代码将该日期解析为Date对象

SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
java.util.Date d = df.parse(date);

Okay so now we have a date object of our actual date, Now lets format it to our new date. 好的,现在我们有了一个实际日期的日期对象,现在让我们将其格式化为新日期。

String finalDate = new SimpleDateFormat("yyyy-MM-dd").format(d);

2. Using LocalDate and DateTimeFormatter 2.使用LocalDate和DateTimeFormatter

Alright here we define our date again and 2 DateTimeFormatter. 好了,我们再次定义日期和2 DateTimeFormatter。

DateTimeFormatter oldFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

The first formatter is our old date format, and the second one is the new one that we are gonna convert the old date into. 第一个格式化程序是我们的旧日期格式,第二个格式化程序是我们将旧日期转换成的新格式。

Alright lets use them now! 好吧,现在就使用它们!

Now we make a new LocalDate object using our oldFormatter by parsing our dateString with the oldFormatter object 现在我们做一个新的LocalDate使用我们的oldFormatter对象通过解析我们dateStringoldFormatter对象

LocalDate dateTime = LocalDate.parse(date, oldFormatter);

Alright now lets format it. 现在,让我们对其进行格式化。

String reformattedDate = dateTime.format(newFormatter);

as simple as that! 就如此容易! Here is the full code. 这是完整的代码。

String date = "11-12-2018";
DateTimeFormatter oldFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate dateTime = LocalDate.parse(date, oldFormatter);
String reformattedDate = dateTime.format(newFormatter);
System.out.println(reformattedDate);

3. Using String::Split 3.使用String :: Split

Okay this part is pretty simple. 好的,这部分非常简单。 Lets split the date using - 让我们使用-分割日期

String[] dates = date.split("-");

We already know the order of the date lets format it using String::format 我们已经知道日期的顺序可以使用String::format对其进行String::format

String reformattedDate = String.format("%s-%s-%s", dates[2], dates[1], dates[0]);

Here is the full code 这是完整的代码

String date = "11-12-2018";
String[] dates = date.split("-");
String reformattedDate = String.format("%s-%s-%s", dates[2], dates[1], dates[0]);
System.out.println(reformattedDate);

Try code below that will work for your case: 请尝试以下适合您情况的代码:

First parse your input format from string, 首先从字符串解析您的输入格式,

String date = "11-12-2018";
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");

Then convert it to desired format, 然后将其转换为所需的格式,

Date dateTobeParse = null;
try {
    dateTobeParse = df.parse(date);
} catch (ParseException e) {
    e.printStackTrace();
}
if (dateTobeParse != null) {
    SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd");
    String outputDate = outFormat.format(dateTobeParse);
}

This is the common function which I use for date and time conversion 这是我用于日期和时间转换的常用功能

public String convertDateAndTime(String date, String oldFormat, String newFormat) {
        SimpleDateFormat sdf = new SimpleDateFormat(oldFormat);
        Date currentdate;
        String converted = "";
        try {
            currentdate = sdf.parse(date);
            SimpleDateFormat sdf2 = new SimpleDateFormat(newFormat);
            converted = sdf2.format(currentdate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return converted;
    }

You just have to pass the date string and their old and new formats. 您只需要传递日期字符串以及它们的新旧格式。 In your case call this function like this 在您的情况下,请像这样调用此函数

String converteddate = convertDateAndTime("11-12-2018","dd-mm-yyyy","yyyy-MM-dd");

Try the code below that will work 尝试下面的代码将起作用

1) Make method like below 1)制作方法如下

public String changeDateFormat(String currentFormat, String requiredFormat, String dateString) {
        String result = "";

        SimpleDateFormat formatterOld = new SimpleDateFormat(currentFormat, Locale.getDefault());
        SimpleDateFormat formatterNew = new SimpleDateFormat(requiredFormat, Locale.getDefault());
        Date date = null;
        try {
            date = formatterOld.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (date != null) {
            result = formatterNew.format(date);
        }
        return result;
    }//end of changeDateFormat()

1st argument of the method is your current date format in your case it will be 'dd-MM-yyyy' 该方法的第一个参数是您当前的日期格式(在您的情况下为“ dd-MM-yyyy”)

2nd argument is output or requires date format in your case it will be 'yyyy-MM-dd' 根据您的情况,第二个参数是输出或需要日期格式,它将是'yyyy-MM-dd'

3rd argument is your date that you want to change the format 第三个参数是您要更改格式的日期

2) Run the method like below 2)运行如下方法

String oldFormatDate = "11-12-2018";
String myDate = changeDateFormat("dd-MM-yyyy", "yyyy-MM-dd", oldFormatDate);
Log.d(TAG, "Old formatted Date : " + oldFormatDate);
Log.d(TAG, "New Date is : " + myDate);

3) Output: 3)输出:

Old formatted Date : 11-12-2018
New Date is : 2018-12-11

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM