Going from MM/DD/YYYY to DD-MMM-YYYY in java

我的未来我决定 提交于 2020-01-10 01:25:09

问题


Is there a method in Java that I can use to convert MM/DD/YYYY to DD-MMM-YYYY?

For example: 05/01/1999 to 01-MAY-99

Thanks!


回答1:


Use a SimpleDateFormat to parse the date and then print it out with a SimpleDateFormat withe the desired format.

Here's some code:

    SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
    SimpleDateFormat format2 = new SimpleDateFormat("dd-MMM-yy");
    Date date = format1.parse("05/01/1999");
    System.out.println(format2.format(date));

Output:

01-May-99



回答2:


Try this,

Date currDate = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String strCurrDate = dateFormat.format(currDate);
System.out.println("strCurrDate->"+strCurrDate);



回答3:


java.time

You should use java.time classes with Java 8 and later. To use java.time, add:

import java.time.* ;

Below is an example, how you can format date.

DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
String date = "15-Oct-2018";
LocalDate localDate = LocalDate.parse(date, formatter);

System.out.println(localDate); 
System.out.println(formatter.format(localDate));



回答4:


Try this

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // Set your date format
        String currentData = sdf.format(new Date());
        Toast.makeText(getApplicationContext(), ""+currentData,Toast.LENGTH_SHORT ).show();



回答5:


final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate localDate = LocalDate.now();
System.out.println("Formatted Date: " + formatter.format(localDate));

Java 8 LocalDate




回答6:


Below should work.

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
Date oldDate = df.parse(df.format(date)); //this date is your old date object



回答7:


formatter = new SimpleDateFormat("dd-MMM-yy");


来源:https://stackoverflow.com/questions/4169634/going-from-mm-dd-yyyy-to-dd-mmm-yyyy-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!