0

I've set an AlertDialog.builder in which there is an input, to obtain a date from the user. Currently, it's set like that:

input.setInputType(InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_NORMAL);

What I would like, isn't simply an entire line on which the user has to write. I would like a thing like
Input: __/__/____
Where the user would have to complete with
Input: 18/04/2018

And then I would get the whole thing as a string: "18-04-2018"

What can I do?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
SemAntys
  • 316
  • 2
  • 15
  • 1
    refer this [Answer](https://stackoverflow.com/a/16889503/6454463) – Rutvik Bhatt Aug 31 '18 at 09:54
  • Tip: When saving or exchanging date-time values as text, use the standard [ISO 8601](https://en.m.wikipedia.org/wiki/ISO_8601) formats. For a date, that would be YYYY-MM-DD format such as `2018-04-18`. The java.time classes use these formats by default when parsing/generating strings. `LocalDate.parse( "2018-04-18" )` – Basil Bourque Aug 31 '18 at 14:53

2 Answers2

1

You can parse the string to LocalDate then format to desired format, or you can just replace / with -:

String input = "18/04/2018";
String outPut;

// first approach
LocalDate localDate = LocalDate.parse(input, DateTimeFormatter.ofPattern("dd/MM/yyyy"));
outPut = localDate.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));

// second approach
outPut = input.replaceAll("/", "-");
xingbin
  • 27,410
  • 9
  • 53
  • 103
0

You have to use SimpleDateFormat which will change the format of date. have look this

public static String changeDateToTimeStamp(String date){
        DateFormat inputFormat = new SimpleDateFormat("dd/mm/yyyy");
        DateFormat outputFormat = new SimpleDateFormat("dd-mm-yyyy");

        Date date1 = null;
        try {
            date1 = inputFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
       return outputFormat.format(date1);
    }

this method will return date like "18-04-2018". Hope it will help you!

Hemant Parmar
  • 3,924
  • 7
  • 25
  • 49
  • 1
    Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Yes, you can use it on Android. For older Android see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Aug 31 '18 at 11:14