如何字符串转换为日期格式的android [英] How to convert String to Date format in android

查看:121
本文介绍了如何字符串转换为日期格式的android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 String testDateString = "02/04/2014";
 DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); 

 Date d1 = df.parse(testDateString);
 String date = df.format(d1);

输出字符串:2014年2月4日

在此输出日期字符串格式化,但我需要格式化日期值(2014年2月4日)。

In this output date is String formated, but I need Date Formated value(02/04/2014).

推荐答案

如果你想有一个约会对象,将始终打印你想要的格式,你必须创建该类的一个自己的子类日期并覆盖的toString 那里。

If you want a date object that will always print your desired format, you have to create an own subclass of class Date and override toString there.

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

public class MyDate extends Date {
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

    /*
     * additional constructors
     */

    @Override
    public String toString() {
        return dateFormat.format(this);
    }
}

现在你可以像你一样与日期创建此类之前,你并不需要创建的SimpleDateFormat 每次

Now you can create this class like you did with Date before and you don't need to create the SimpleDateFormat every time.

public static void main(String[] args) {
    MyDate date = new MyDate();
    System.out.println(date);
}

输出为 23/08/2014

这是你贴在你的问题的更新时间是code:

This is the updated code you posted in your question:

String testDateString = "02/04/2014";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); 

MyDate d1 = (MyDate) df.parse(testDateString);
System.out.println(d1);

请注意,你不必叫 df.format(D1)了。 d1.toString()将返回日期的格式化字符串。

Note that you don't have to call df.format(d1) anymore. d1.toString() will return the date as the formated string.

这篇关于如何字符串转换为日期格式的android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆