如何在不使用任何已弃用的类的情况下将日期从一种格式转换为另一种格式的另一种日期对象?

时间:2012-09-19 22:00:18

标签: java

我想将date1格式的日期转换为date2格式的日期对象。

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd, yyyy");
    SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMdd");
    Calendar cal = Calendar.getInstance();
    cal.set(2012, 8, 21);
    Date date = cal.getTime();
    Date date1 = simpleDateFormat.parse(date);
    Date date2 = simpleDateFormat.parse(date1);
    println date1
    println date2

10 个答案:

答案 0 :(得分:106)

使用SimpleDateFormat#format

DateFormat originalFormat = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("yyyyMMdd");
Date date = originalFormat.parse("August 21, 2012");
String formattedDate = targetFormat.format(date);  // 20120821

另请注意,parse需要String,而不是Date对象,该对象已经已解析

答案 1 :(得分:5)

TL;博士

LocalDate.parse( 
    "January 08, 2017" , 
    DateTimeFormatter.ofPattern( "MMMM dd, uuuu" , Locale.US ) 
).format( DateTimeFormatter.BASIC_ISO_DATE ) 

使用java.time

问题和其他答案使用麻烦的旧日期时间类,现在已经遗留下来,取而代之的是java.time类。

您有仅限日期的值,因此请使用仅限日期的类。 LocalDate类表示没有时间且没有时区的仅限日期的值。

String input = "January 08, 2017";
Locale l = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMMM dd, uuuu" , l );
LocalDate ld = LocalDate.parse( input , f );

您所需的输出格式由ISO 8601标准定义。对于仅限日期的值,“扩展”格式为YYYY-MM-DD,例如2017-01-08,并且最小化分隔符使用的“基本”格式为YYYYMMDD,例如20170108

我强烈建议使用扩展格式以提高可读性。但是如果你坚持使用基本格式,那格式化程序就被预定义为名为DateTimeFormatterBASIC_ISO_DATE类的常量。

String output = ld.format( DateTimeFormatter.BASIC_ISO_DATE );

请参阅此code run live at IdeOne.com

  

ld.toString():2017-01-08

     

输出:20170108

关于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

答案 2 :(得分:2)

使用Java 8,我们可以实现如下:

private static String convertDate(String strDate) 
{
    //for strdate = 2017 July 25

    DateTimeFormatter f = new DateTimeFormatterBuilder().appendPattern("yyyy MMMM dd")
                                        .toFormatter();

    LocalDate parsedDate = LocalDate.parse(strDate, f);
    DateTimeFormatter f2 = DateTimeFormatter.ofPattern("MM/d/yyyy");

    String newDate = parsedDate.format(f2);

    return newDate;
}

输出将是:" 07/25/2017和#34;

答案 3 :(得分:1)

请参阅以下方法。它将您的日期String作为argument1,您需要指定日期的现有格式 作为参数2,结果(预期)格式为参数3。

请参阅此链接以了解各种格式: Available Date Formats

public static String formatDateFromOnetoAnother(String date,String givenformat,String resultformat) {

    String result = "";
    SimpleDateFormat sdf;
    SimpleDateFormat sdf1;

    try {
        sdf = new SimpleDateFormat(givenformat);
        sdf1 = new SimpleDateFormat(resultformat);
        result = sdf1.format(sdf.parse(date));
    }
    catch(Exception e) {
        e.printStackTrace();
        return "";
    }
    finally {
        sdf=null;
        sdf1=null;
    }
    return result;
}

答案 4 :(得分:0)

希望这会对某人有所帮助。

 public static String getDate(
        String date, String currentFormat, String expectedFormat)
throws ParseException {
    // Validating if the supplied parameters is null 
    if (date == null || currentFormat == null || expectedFormat == null ) {
        return null;
    }
    // Create SimpleDateFormat object with source string date format
    SimpleDateFormat sourceDateFormat = new SimpleDateFormat(currentFormat);
    // Parse the string into Date object
    Date dateObj = sourceDateFormat.parse(date);
    // Create SimpleDateFormat object with desired date format
    SimpleDateFormat desiredDateFormat = new SimpleDateFormat(expectedFormat);
    // Parse the date into another format
    return desiredDateFormat.format(dateObj).toString();
}

答案 5 :(得分:0)

试试这个

这是将一种日期格式更改为另一种日期格式的最简单方法

public String changeDateFormatFromAnother(String date){
    @SuppressLint("SimpleDateFormat") DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    @SuppressLint("SimpleDateFormat") DateFormat outputFormat = new SimpleDateFormat("dd MMMM yyyy");
    String resultDate = "";
    try {
        resultDate=outputFormat.format(inputFormat.parse(date));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return resultDate;
}

答案 6 :(得分:0)

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

             String fromDateFormat = "dd/MM/yyyy";
             String fromdate = 15/03/2018; //Take any date

             String CheckFormat = "dd MMM yyyy";//take another format like dd/MMM/yyyy
             String dateStringFrom;

             Date DF = new Date();


              try
              {
                 //DateFormatdf = DateFormat.getDateInstance(DateFormat.SHORT);
                 DateFormat FromDF = new SimpleDateFormat(fromDateFormat);
                 FromDF.setLenient(false);  // this is important!
                 Date FromDate = FromDF.parse(fromdate);
                 dateStringFrom = new 
                 SimpleDateFormat(CheckFormat).format(FromDate);
                 DateFormat FromDF1 = new SimpleDateFormat(CheckFormat);
                 DF=FromDF1.parse(dateStringFrom);
                 System.out.println(dateStringFrom);
              }
              catch(Exception ex)
              {

                  System.out.println("Date error");

              }

output:- 15/03/2018
         15 Mar 2018

答案 7 :(得分:0)

相当于João Silva的答案的科特琳

 fun getFormattedDate(originalFormat: SimpleDateFormat, targetFormat: SimpleDateFormat, inputDate: String): String {
    return targetFormat.format(originalFormat.parse(inputDate))
}

用法(在Android中):

getFormattedDate(
            SimpleDateFormat(FormatUtils.d_MM_yyyy, Locale.getDefault()),
            SimpleDateFormat(FormatUtils.d_MMM_yyyy, Locale.getDefault()),
            dateOfTreatment
    )

注意:常量值:

// 25 Nov 2017
val d_MMM_yyyy = "d MMM yyyy"

// 25/10/2017
val d_MM_yyyy = "d/MM/yyyy"

答案 8 :(得分:0)

  private String formatDate(String date, String inputFormat, String outputFormat) {

    String newDate;
    DateFormat inputDateFormat = new SimpleDateFormat(inputFormat);
    inputDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    DateFormat outputDateFormat = new SimpleDateFormat(outputFormat);
    try {
        newDate = outputDateFormat.format((inputDateFormat.parse(date)));
    } catch (Exception e) {
        newDate = "";
    }
    return newDate;

}

答案 9 :(得分:-1)

{
  "queryType": "groupBy",
  "dataSource":{
    "type": "query",
    "query": {
      "queryType": "groupBy",
      "dataSource": "yourDataSource",
      "granularity": "--",
      "dimensions": ["country", "website"],
      "aggregations": [
        {
            "type": "longSum",
            "name": "PV",
            "fieldName": "PV"
        }
      ],
      "intervals": [ "2012-01-01T00:00:00.000/2020-01-03T00:00:00.000" ]
    }
  },
  "granularity": "all",
  "dimensions": ["country"],
  "aggregations": [
    ----
  ],
  "intervals": [ "2012-01-01T00:00:00.000/2020-01-03T00:00:00.000" ]
}