How to get Date from a String in android?

时间:2016-12-09 13:02:38

标签: android android-studio

I want to get date from a give string. Suppose we have a string 09-Dec-2016 12:00:00 AM I want to display only 30-Dec-2016

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView=(TextView)findViewById(R.id.date);

       // String strCurrentDate = "Wed, 18 Apr 2012 07:55:29 +0000";
        String strCurrentDate = "30-Dec-2016 12:00:00 AM";
       // SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss Z");
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss Z");
        Date newDate = null;
        try {
            newDate = format.parse(strCurrentDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        format = new SimpleDateFormat("dd-MMM-yyyy hh:mm a");
        String date = format.format(newDate);
        textView.setText(date);


    }

I want to display date like this 30-Dec-2016

5 个答案:

答案 0 :(得分:1)

这应该有用。

SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm a");
Date date = sdf.parse(inputDateString);
sdf = new SimpleDateFormat("dd-MMM-yyyy");
String outputString  = sdf.format(date);

答案 1 :(得分:0)

执行此操作:

String currDate = "09-Dec-2016 12:00:00 AM";
String date = currDate.split("\\s")[0];

答案 2 :(得分:0)

public Date String_date(String date) 
{
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd kk-mm");
    Date myDate = null;
    try {
        myDate = dateFormat.parse(date);

        return myDate;

    } catch (ParseException e) {
        e.printStackTrace();
    }
    return myDate;

}

答案 3 :(得分:0)

试试这个:

    String strCurrentDate = "30-Dec-2016 12:00:00 AM";
    SimpleDateFormat formatParse = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss a",Locale.getDefault());
    Date newDate = null;
    try {
        newDate = formatParse.parse(strCurrentDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());
    String date = format.format(newDate);
    textView.setText(date);

PS。 formats eg.

答案 4 :(得分:0)

// parse DatetừDate sang String SimpleDateFormat格式=新的SimpleDateFormat(“ dd-MM-yyyy”);

        Date newdate = new Date(Long.parseLong(tt.getThoiGian()));



        format = new SimpleDateFormat("dd-MM-yyyy");
        String date1 = format.format(newdate);
        txtThoiGian.setText(date1);