Angular 4中传递ngx-bootstrap日期选择器值给WebAPI时如何仅提取日期
如何在Angular 4中提取ngx-bootstrap日期选择器的日期部分(去掉时间)
嘿,这个问题我之前在项目里也碰到过!ngx-bootstrap的日期选择器默认返回完整的Date对象,所以传给WebAPI的时候会附带时间信息,这里有几个实用的办法帮你只提取日期部分:
方法1:用Angular内置的DatePipe快速格式化
这是最省心的方案,Angular自带的DatePipe能帮你一键搞定日期格式化。
- 首先在你的组件里引入并注册DatePipe(Angular 4需要手动添加到providers里):
import { DatePipe } from '@angular/common'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', providers: [DatePipe] // 注册DatePipe }) export class YourComponent { constructor(private datePipe: DatePipe) {} // 当日期选择器的值变化时调用 onDateChange(selectedDate: Date) { // 把日期格式化为'yyyy-MM-dd'格式的字符串 const dateOnly = this.datePipe.transform(selectedDate, 'yyyy-MM-dd'); // 现在dateOnly就是不带时间的纯日期字符串,比如'2018-03-02',直接传给API就行 } }
方法2:手动拼接日期字符串(无需依赖内置管道)
如果你不想用DatePipe,也可以直接操作Date对象的原生方法来拼接日期:
// 写一个格式化函数 formatToDateOnly(date: Date): string { const year = date.getFullYear(); // 注意月份是从0开始的,所以要加1,还要补零保证两位数 const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; } // 使用示例 onDateChange(selectedDate: Date) { const dateOnly = this.formatToDateOnly(selectedDate); // 将dateOnly传递给WebAPI }
方法3:一行代码快速截取ISO字符串
这是最简洁的小技巧,利用Date对象的toISOString()方法返回的格式,直接截取日期部分:
onDateChange(selectedDate: Date) { // toISOString()返回的格式是'2018-03-02T09:15:02.000Z',用split('T')分割后取第一个元素 const dateOnly = selectedDate.toISOString().split('T')[0]; // 得到的就是'2018-03-02' }
另外,你也可以在ngx-bootstrap的日期选择器模板里配置dateInputFormat,让输入框显示纯日期,但要注意它返回的依然是Date对象,所以还是需要在传递给API前做上述处理:
<input type="text" bsDatepicker [(bsValue)]="selectedDate" [dateInputFormat]="'YYYY-MM-DD'">
这些方法都能完美解决你的问题,选一个最适合你项目风格的就行~
内容的提问来源于stack exchange,提问作者Pravin
相关产品推荐
相关产品推荐

