【问题标题】:I want to Change Date Format我想更改日期格式
【发布时间】:2015-10-25 03:44:32
【问题描述】:

我想将日期 2015 年 3 月 7 日更改为 2015 年 8 月 3 日

我有类似的日期值:

int day=3,month =7 ,year =2015

【问题讨论】:

  • 好的。您对 API 文档和网络搜索的审查发现了什么?您尝试使用该信息的代码是什么样的?它带来了哪些出乎你意料的结果?
  • 只需使用以下格式 dd MMM YYYY,它会将日期转换为所需的格式
  • 谢谢@SSH 它的工作谢谢兄弟。但是如何在今天添加我选择的日期?
  • 您的今天对象必须具有您选择日期的格式,而不是您可以将日期设置为今天对象,

标签: java android


【解决方案1】:

这是利用新的date and formatter classes in Java 8:

LocalDateTime date = LocalDate.of(2015, Month.JULY, 3);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dMMM yyyy");
String formattedDateTime = date.format(formatter); // "3Aug 2015"

【讨论】:

    【解决方案2】:

    您需要使用真实的 Date 对象,然后对其进行格式化:

    Calendar cal = GregorianCalendar.getInstance();
    cal.set(Calendar.DAY_OF_MONTH, 3);
    cal.set(Calendar.MONTH, 6);
    cal.set(Calendar.YEAR, 2015);
    SimpleDateFormat format = new SimpleDateFormat("DD_MMM_YYYY");
    format.format(cal.getTime());
    

    【讨论】:

    • 这是 Java 8 之前 JDK 的完整 Java 示例。
    【解决方案3】:

    下面的示例代码很简单:-

    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    
    public class DateFormatter {
    
        public static void main(String[] args) {
    
            Calendar cal = Calendar.getInstance();
            cal.set(2015, 7, 3);
    
            SimpleDateFormat sdf = new SimpleDateFormat("dMMM yyyy");
    
            System.out.println("Formatted Date :  " + sdf.format(cal.getTime()));
        }
    
    }
    

    输出

    Formatted Date :  3Aug 2015
    

    【讨论】:

      【解决方案4】:
      // Convert all the value to string, then concate the value in the following format
      // date Month year, then use Simpledateformat as dd MMM yyyy
      
      DateFormat originalFormat = new SimpleDateFormat("dd MM yyyy", Locale.ENGLISH);
      DateFormat targetFormat = new SimpleDateFormat("dd MMM yyyy");
      Date date = originalFormat.parse("3 7 2015");
      String formattedDate = targetFormat.format(date);
      

      【讨论】:

        【解决方案5】:

        如果变量中有日期值,则可以使用数组来获取月份的值。

        String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
        int day = 5;
        int month = 4;
        int year = 1994;
        
        System.out.printnln("The Date is " + day + months[month - 1]+ year);
        

        【讨论】:

          猜你喜欢
          • 2014-03-02
          • 2014-12-01
          • 2018-06-25
          • 2013-06-05
          • 1970-01-01
          • 1970-01-01
          • 2020-02-19
          • 2011-06-05
          • 2016-11-22
          相关资源
          最近更新 更多