bind date to inpubtbox with angular dart

Issue

I’m building a webapp in which are inputboxes with a date. How can I bind the data to my background code?
I tried just doing it directly but i guess an inputbox can only handle strings so a made a convert to string method and so on.

<div>
    <label>start date: </label>
    <input [(ngModel)]="item.stringStartDate" placeholder="start date" type="date">
</div>


void set startDate(DateTime startDate)
{
    _startDate = startDate;
}

void set stringStartDate(String startDate)
{
    this.startDate = parseDate(startDate);
}


static DateTime parseDate(String formattedString)
{
    final RegExp r = new RegExp(
        r'^(\d\d)-?(\d\d)-?([+-]?\d{4,6})');

    Match match = r.firstMatch(formattedString);
    if (match != null)
    {
        int years = int.parse(match[3]);
        int month = int.parse(match[2]);
        int day = int.parse(match[1]);

        return new DateTime(years, month, day);
    }
    else
    {
        throw new FormatException("Invalid date format", formattedString);
    }
}

static String dateToString(DateTime date){
    if (date == null)
        return null;

    String ret = "${date.year}/";

    if (date.month < 10)
        ret+="0";
    ret+="${date.month}/";

    if (date.day < 10)
        ret += "0";
    ret+="${date.day}";

    return ret;
}

Solution

it should be separated by - instead of /

you can use toIso8601String and substring

DateTime _date = new DateTime.now();

String get date => _date.toIso8601String().substring(0, 10);

void set date(value) {
  if (value is DateTime) {
    _date = value;
  } else if (value is String) {
    _date = DateTime.parse(value);
  }
}

Answered By – Hadrien Lejard

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.