2017-04-03 93 views
1

我正在建立一個Web應用程序,其中有一個日期的輸入框。我怎樣才能將數據綁定到我的後臺代碼? 我試着直接做,但我猜一個輸入框只能處理字符串,所以一個轉換爲字符串方法等。綁定日期到角度飛鏢inpubtbox

<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; 
} 

回答

1

應該由-分開,而不是/

可以使用toIso8601Stringsubstring

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); 
    } 
} 
+0

的伎倆感謝 –