I have two strings. A date string and a time string, these need to be concatenated together to form a valid datetime. The below code works but looks a bit messy and a bit like a hack, is there a better way?
.ForMember(dest => dest.ValidFrom, src => src.MapFrom(m =>
DateTime.Parse(m.ValidFromDate.Contains("T") ?
m.ValidFromDate.Remove(m.ValidFromDate.LastIndexOf("T", StringComparison.Ordinal) + 1)
:
m.ValidFromDate
+ " " +
m.ValidFromTime)))
Here is how I fixed this in the end:
date/time converter:
import moment from 'moment';
export class DateTimeFormat {
format(date, time) {
var dateFormatted;
if (typeof(date) === 'string')
{
// Must have come from the DB
dateFormatted = date;
}
else
{
// Must be an object from a calendar etc
dateFormatted = moment(date).format('DD/MM/YYYY');
}
return moment(dateFormatted + 'T' + time, 'DD/MM/YYYY HH:mm:ss');
}
}
Code behind for the form:
this.validator = this.validation.on(this)
.ensure('baseContent.ValidFromDate', (config) => { config.computedFrom(['baseContent.ValidFromDate', 'baseContent.ValidFromTime', 'baseContent.ValidToDate', 'baseContent.ValidToTime']) })
.if(() => {
return this.baseContent.ValidFromDate !== null && this.baseContent.ValidFromTime !== null && this.baseContent.ValidToDate !== null && this.baseContent.ValidToTime !== null })
.passes( () => { return this.datetimeformat.format(this.baseContent.ValidFromDate, this.baseContent.ValidFromTime) < this.datetimeformat.format(this.baseContent.ValidToDate, this.baseContent.ValidToTime) })
.withMessage('< Valid To')
.endIf()