Error in date validation MVC - asp.net-mvc

My model class property looks like this
public DateTime PurchaseDate { get; set; }
and inside view
#Html.TextBoxFor(model => model.PurchaseDate, new { #class = "form-control date-picker" })
#Html.ValidationMessageFor(model => model.PurchaseDate)
and I am giving a date like this in form
19/06/2015
But it gives validation message and not allows page to be submitted, message is like this
The field PurchaseDate must be a date.
if I give date in mm/dd/yyyy format it works. Can anyone point out what I am doing wrong here?

The client side error is occurring because by default jquery.validate tests the value using the MM/dd/yyyy format. You can override the $.validator.addMethod('date', function (value, element) function to test that the value is in the dd/MM/yyyy you expect. Note the following code is from my own jquery plugin associated with a #Html.DatePickerFor() helper method which renders a data-dateformat attribute in the output based on the servers culture, so it may be an overkill for your needs
Add the following scripts (not in document.ready, but after jquery.validate.unobtrusive)
Date.prototype.isValid = function () {
return !isNaN(this.getTime());
}
globalDate = function (value, formatString) {
// Initialise a new date
var date = new Date(0);
if (value == undefined) {
// Return todays date
return date;
}
// Get the components of the format
// The separator can be forward slash, hyphen, dot and/or space
var regex = new RegExp(/([dMy]+)([\s/.-]+)([dMy]+)([\s/.-]+)([dMy]+)/);
//var format = regex.exec(this.inputFormat);
var format = regex.exec(formatString);
// Get the components of the value
regex = new RegExp(/(\d+)([\s/.-]+)(\d+)([\s/.-]+)(\d+)/);
value = regex.exec(value);
// Check the value is valid
if (value === null || value[2] !== format[2] || value[4] !== format[4]) {
// Its not valid
date.setTime(Number.NaN);
return date;
}
// TODO: What if year entered as 2 digits?
var day = Number.NaN;
var month = Number.NaN;
var year = Number.NAN;
if (format[1].charAt(0) === 'd') {
// little-endian (day, month, year)
day = parseInt(value[1]);
month = parseInt(value[3]) - 1;
year = parseInt(value[5]);
} else if (format[1].charAt(0) === 'M') {
// middle-endian (month, day, year)
day = parseInt(value[3]);
month = parseInt(value[1]) - 1;
year = parseInt(value[5]);
} else {
// big endian (year, month, day)
day = parseInt(value[5]);
month = parseInt(value[3]) - 1;
year = parseInt(value[1]);
}
date.setFullYear(year);
date.setMonth(month);
date.setDate(day);
// Check its valid
if (date.getDate() !== day || date.getMonth() !== month || date.getFullYear() !== year) {
date.setTime(Number.NaN);
return date;
}
return date;
}
$.validator.addMethod('date', function (value, element) {
var format = "dd/MM/yyyy";
return this.optional(element) || globalDate(value, format).isValid();
}
If you only ever want to test for the format dd/MM/yyyy, then you could simplify the globalDate() function by just using
var date = new Date();
date.setHours(0, 0, 0, 0);
var components = value.split('/');
var day = components[0];
var month = components[1];
var year = components[2];
date.setFullYear(year);
....
Edit
Further to OP's comments regarding server side validation failing, the server culture needs to accept a date string in the format dd/MM/yyyy. In the web.config.cs file
<system.web>
<globalization culture="en-AU" uiCulture="en-AU"/> // adjust to your culture code
....

If you want to explicitly set the expected date format for your model property then you can do this using the DisplayAttribute
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime PurchaseDate { get; set; }
Otherwise, the current culture of the server would be used (which in your case happens to be MM/dd/yyyy).
It appears that in order for client-side validation to respect the DataFormatString we need to use EditorFor in place of TextBoxFor
#Html.EditorFor(model => model.PurchaseDate, new { #class = "form-control date-picker" })
#Html.ValidationMessageFor(model => model.PurchaseDate)

Related

How to disable the past dates in the Kendo date picker?

How to disable the past dates in the Kendo date picker ? ( Date Picker validation)
That will allow the user to select only the current date and future date.
In the HTML :
#Html.EditorFor(Model => Model.AppointmentDate)
In the JQuery :
$('#AppointmentDatee').data('kendoDatePicker')
The shortest way to disable past dates is using min parameter with current date value:
var presentDate = new Date();
$(function () {
var datepicker = $('#AppointmentDate').kendoDatePicker({
value: presentDate,
min: presentDate,
}).data('kendoDatePicker');
});
If you're using Razor with #Html.Kendo() helper, use DatePickerBuilderBase.Min() method:
#(Html.Kendo().DatePicker().Name("AppointmentDate").Min(DateTime.Today))
However, the min parameter will remove all disabled past dates (i.e. they're not shown in calendar view). If you want to show disabled dates but the user cannot interact with them (by clicking the date), use k-state-disabled CSS class in empty option inside month parameter:
var datepicker = $('#AppointmentDate2').kendoDatePicker({
value: presentDate,
min: presentDate,
month: {
empty: '<div class="k-state-disabled">#= data.value #</div>'
}
}).data('kendoDatePicker');
If #(Html.Kendo()) helper is used, use DisabledDates to call a function which disables past dates like example below:
<script>
var getPastDates = function(begin, end) {
for (var dtarr = [], date = start; date < end; date.setDate(date.getDate() + 1)) {
dtarr.push(new Date(dt));
}
return dtarr;
}
function disablePastDates(date) {
var pastDate = getPastDates(new Date('0001-01-01T00:00:00Z'), new Date());
if (date && compareDates(date, dates)) {
return true;
}
else {
return false;
}
}
function compareDates(date, dates) {
for (var i = 0; i < dates.length; i++) {
if (dates[i].getDate() == date.getDate() &&
dates[i].getMonth() == date.getMonth() &&
dates[i].getYear() == date.getYear()) {
return true;
}
}
}
</script>
Helper usage:
#(Html.Kendo().DatePicker().Name("AppointmentDate").DisableDates("disablePastDates"))
Working examples:
JSFiddle demo 1 (hidden past dates)
JSFiddle demo 2 (grayed-out past dates)
References:
Kendo.Mvc.UI.Fluent.DatePickerBuilderBase.Min(DateTime)
Show Out-of-Range Dates as Disabled
Kendo MVC DatePicker - Disable dates
Similar issue (with different approach):
How to disable past dates without hiding them in Kendo date picker?
if you use jquery for your kendoDatePicker , this code may help you!
$("#MyDatapickerElement").kendoDatePicker({
value: new Date(),
disableDates: function (date) {
if (date <= new Date()) {
return true;
} else {
return false;
}
}
});
If using Html.Kendo().DatePicker() you can show the disabled dates using the MonthTemplate. Example below shows the Minimum Date set to DateTime.Today and sets the MonthTemplate to show past dates as disabled.
Html.Kendo().DatePicker()
.Name("MyDate")
.Min(DateTime.Today)
.MonthTemplate(m=>m
.Empty("<div class=\"k-state-disabled\">#= data.value #</div>")
)

Converting timestamp

I couldn't find a solution to this, I'm grabbing data from firebase and one of the fields is a timestamp which looks like this -> 1522129071. How to convert it to a date?
Swift example (works) :
func readTimestamp(timestamp: Int) {
let now = Date()
let dateFormatter = DateFormatter()
let date = Date(timeIntervalSince1970: Double(timestamp))
let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .weekOfMonth])
let diff = Calendar.current.dateComponents(components, from: date, to: now)
var timeText = ""
dateFormatter.locale = .current
dateFormatter.dateFormat = "HH:mm a"
if diff.second! <= 0 || diff.second! > 0 && diff.minute! == 0 || diff.minute! > 0 && diff.hour! == 0 || diff.hour! > 0 && diff.day! == 0 {
timeText = dateFormatter.string(from: date)
}
if diff.day! > 0 && diff.weekOfMonth! == 0 {
timeText = (diff.day == 1) ? "\(diff.day!) DAY AGO" : "\(diff.day!) DAYS AGO"
}
if diff.weekOfMonth! > 0 {
timeText = (diff.weekOfMonth == 1) ? "\(diff.weekOfMonth!) WEEK AGO" : "\(diff.weekOfMonth!) WEEKS AGO"
}
return timeText
}
My attempt at Dart:
String readTimestamp(int timestamp) {
var now = new DateTime.now();
var format = new DateFormat('HH:mm a');
var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp);
var diff = date.difference(now);
var time = '';
if (diff.inSeconds <= 0 || diff.inSeconds > 0 && diff.inMinutes == 0 || diff.inMinutes > 0 && diff.inHours == 0 || diff.inHours > 0 && diff.inDays == 0) {
time = format.format(date); // Doesn't get called when it should be
} else {
time = diff.inDays.toString() + 'DAYS AGO'; // Gets call and it's wrong date
}
return time;
}
And it returns dates/times that are waaaaaaay off.
UPDATE:
String readTimestamp(int timestamp) {
var now = new DateTime.now();
var format = new DateFormat('HH:mm a');
var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp * 1000);
var diff = date.difference(now);
var time = '';
if (diff.inSeconds <= 0 || diff.inSeconds > 0 && diff.inMinutes == 0 || diff.inMinutes > 0 && diff.inHours == 0 || diff.inHours > 0 && diff.inDays == 0) {
time = format.format(date);
} else {
if (diff.inDays == 1) {
time = diff.inDays.toString() + 'DAY AGO';
} else {
time = diff.inDays.toString() + 'DAYS AGO';
}
}
return time;
}
Your timestamp format is in fact in Seconds (Unix timestamp) as opposed to microseconds. If so the answer is as follows:
Change:
var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp);
to
var date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
From milliseconds:
var millis = 978296400000;
var dt = DateTime.fromMillisecondsSinceEpoch(millis);
// 12 Hour format:
var d12 = DateFormat('MM/dd/yyyy, hh:mm a').format(dt); // 12/31/2000, 10:00 PM
// 24 Hour format:
var d24 = DateFormat('dd/MM/yyyy, HH:mm').format(dt); // 31/12/2000, 22:00
From Firestore:
Map<String, dynamic> map = docSnapshot.data()!;
DateTime dt = (map['timestamp'] as Timestamp).toDate();
Converting one format to other:
12 Hour to 24 Hour:
var input = DateFormat('MM/dd/yyyy, hh:mm a').parse('12/31/2000, 10:00 PM');
var output = DateFormat('dd/MM/yyyy, HH:mm').format(input); // 31/12/2000, 22:00
24 Hour to 12 Hour:
var input = DateFormat('dd/MM/yyyy, HH:mm').parse('31/12/2000, 22:00');
var output = DateFormat('MM/dd/yyyy, hh:mm a').format(input); // 12/31/2000, 10:00 PM
Use intl package (for formatting)
Full code for anyone who needs it:
String readTimestamp(int timestamp) {
var now = DateTime.now();
var format = DateFormat('HH:mm a');
var date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
var diff = now.difference(date);
var time = '';
if (diff.inSeconds <= 0 || diff.inSeconds > 0 && diff.inMinutes == 0 || diff.inMinutes > 0 && diff.inHours == 0 || diff.inHours > 0 && diff.inDays == 0) {
time = format.format(date);
} else if (diff.inDays > 0 && diff.inDays < 7) {
if (diff.inDays == 1) {
time = diff.inDays.toString() + ' DAY AGO';
} else {
time = diff.inDays.toString() + ' DAYS AGO';
}
} else {
if (diff.inDays == 7) {
time = (diff.inDays / 7).floor().toString() + ' WEEK AGO';
} else {
time = (diff.inDays / 7).floor().toString() + ' WEEKS AGO';
}
}
return time;
}
Thank you Alex Haslam for the help!
if anyone come here to convert firebase Timestamp here this will help
Timestamp time;
DateTime.fromMicrosecondsSinceEpoch(time.microsecondsSinceEpoch)
If you are using firestore (and not just storing the timestamp as a string) a date field in a document will return a Timestamp. The Timestamp object contains a toDate() method.
Using timeago you can create a relative time quite simply:
_ago(Timestamp t) {
return timeago.format(t.toDate(), 'en_short');
}
build() {
return Text(_ago(document['mytimestamp'])));
}
Make sure to set _firestore.settings(timestampsInSnapshotsEnabled: true); to return a Timestamp instead of a Date object.
To convert Firestore Timestamp to DateTime object just use .toDate() method.
Example:
Timestamp now = Timestamp.now();
DateTime dateNow = now.toDate();
As you can see in docs
Just make sure to multiply by the right factor:
Micro: multiply by 1000000 (which is 10 power 6)
Milli: multiply by 1000 (which is 10 power 3)
This is what it should look like in Dart:
var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp * 1000000);
Or
var date = new DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
meh, just use https://github.com/andresaraujo/timeago.dart library; it does all the heavy-lifting for you.
EDIT:
From your question, it seems you wanted relative time conversions, and the timeago library enables you to do this in 1 line of code. Converting Dates isn't something I'd choose to implement myself, as there are a lot of edge cases & it gets fugly quickly, especially if you need to support different locales in the future. More code you write = more you have to test.
import 'package:timeago/timeago.dart' as timeago;
final fifteenAgo = DateTime.now().subtract(new Duration(minutes: 15));
print(timeago.format(fifteenAgo)); // 15 minutes ago
print(timeago.format(fifteenAgo, locale: 'en_short')); // 15m
print(timeago.format(fifteenAgo, locale: 'es'));
// Add a new locale messages
timeago.setLocaleMessages('fr', timeago.FrMessages());
// Override a locale message
timeago.setLocaleMessages('en', CustomMessages());
print(timeago.format(fifteenAgo)); // 15 min ago
print(timeago.format(fifteenAgo, locale: 'fr')); // environ 15 minutes
to convert epochMS to DateTime, just use...
final DateTime timeStamp = DateTime.fromMillisecondsSinceEpoch(1546553448639);
How to implement:
import 'package:intl/intl.dart';
getCustomFormattedDateTime(String givenDateTime, String dateFormat) {
// dateFormat = 'MM/dd/yy';
final DateTime docDateTime = DateTime.parse(givenDateTime);
return DateFormat(dateFormat).format(docDateTime);
}
How to call:
getCustomFormattedDateTime('2021-02-15T18:42:49.608466Z', 'MM/dd/yy');
Result:
02/15/21
Above code solved my problem. I hope, this will also help you. Thanks for asking this question.
I don't know if this will help anyone. The previous messages have helped me so I'm here to suggest a few things:
import 'package:intl/intl.dart';
DateTime convertTimeStampToDateTime(int timeStamp) {
var dateToTimeStamp = DateTime.fromMillisecondsSinceEpoch(timeStamp * 1000);
return dateToTimeStamp;
}
String convertTimeStampToHumanDate(int timeStamp) {
var dateToTimeStamp = DateTime.fromMillisecondsSinceEpoch(timeStamp * 1000);
return DateFormat('dd/MM/yyyy').format(dateToTimeStamp);
}
String convertTimeStampToHumanHour(int timeStamp) {
var dateToTimeStamp = DateTime.fromMillisecondsSinceEpoch(timeStamp * 1000);
return DateFormat('HH:mm').format(dateToTimeStamp);
}
int constructDateAndHourRdvToTimeStamp(DateTime dateTime, TimeOfDay time ) {
final constructDateTimeRdv = dateTimeToTimeStamp(DateTime(dateTime.year, dateTime.month, dateTime.day, time.hour, time.minute)) ;
return constructDateTimeRdv;
}
Assuming the field in timestamp firestore is called timestamp, in dart you could call the toDate() method on the returned map.
// Map from firestore
// Using flutterfire package hence the returned data()
Map<String, dynamic> data = documentSnapshot.data();
DateTime _timestamp = data['timestamp'].toDate();
Simply call this method to return your desired DateTime value in String.
String parseTimeStamp(int value) {
var date = DateTime.fromMillisecondsSinceEpoch(value * 1000);
var d12 = DateFormat('MM-dd-yyyy, hh:mm a').format(date);
return d12;
}
Example: if you pass the TimeStamp value 1636786003, you will get the result as
11-12-2021, 10:46PM
If you are here to just convert Timestamp into DateTime,
Timestamp timestamp = widget.firebaseDocument[timeStampfield];
DateTime date = Timestamp.fromMillisecondsSinceEpoch(
timestamp.millisecondsSinceEpoch).toDate();
I tested this one and it works
// Map from firestore
// Using flutterfire package hence the returned data()
Map<String, dynamic> data = documentSnapshot.data();
DateTime _timestamp = data['timestamp'].toDate();
Test details can be found here: https://www.youtube.com/watch?v=W_X8J7uBPNw&feature=youtu.be
Print DateTime, TimeStamp as string from Firebase Firestore:
Timestamp t;
String s;
DateTime d;
//Declaring Variables
snapshots.data.docs[index]['createdAt'] is Timestamp
? t = snapshots.data.docs[index]['createdAt']
: s =
snapshots.data.docs[index]['createdAt'].toString();
//check createdAt field Timestamp or DateTime
snapshots.data.docs[index]['createdAt'] is Timestamp
? d = t.toDate()
: s =
snapshots.data.docs[index]['createdAt'].toString();
print(s.toString()); //Print Date and Time if DateTime
print(d.toString()); //Print Date and Time if TimeStamp
Recently I've faced the same issue. so I'm using simple logic.
Very simple to Convert TimeStamp to DateTime. We can use this get TimeStamp to DateTime format.
In this example, I'm using Firebase.
import 'package:intl/intl.dart'; /// Import this line
TimeStamp timestamp = database.data()["date"] /// Firebase firestore date field value.
//Example Outputs:- Timestamp(seconds=1657706107, nanoseconds=261000000)
DateTime dateTime = timestamp.toDate(); /// It will be return Date and Time Both.
//Example Outputs:- 2022-07-13 15:25:07.261
String dateOnly = DateFormat('dd/MM/yyyy').format(dateTime); /// It will be only return date DD/MM/YYYY format
//Example Outputs:- 13/07/2022
In a single-line code
import 'package:intl/intl.dart'; /// Import this line
String dateOnly = DateFormat('dd/MM/yyyy').format(database.data()["date"].toDate()); /// It will be only return date DD/MM/YYYY format
//Example Outputs:- 13/07/2022
Thanks for visiting and pushing my reputation 😍
Happy Coding Journey...🤗
2022
Actually the Flutter team updated the Timestamp object.
Now if you want to convert from Timestamp to DateTime you can just use this code:
/*you Timestamp instance*/.toDate()
eg. Timestamp.now().toDate()
Viceversa if you want to convert from DateTime to Timestamp you can do:
Timestamp.fromDate(/*your DateTime instance*/)
eg. Timestamp.fromDate(DateTime.now())
Hope you'll find this helpfull.
All of that above can work but for a quick and easy fix you can use the time_formatter package.
Using this package you can convert the epoch to human-readable time.
String convertTimeStamp(timeStamp){
//Pass the epoch server time and the it will format it for you
String formatted = formatTime(timeStamp).toString();
return formatted;
}
//Then you can display it
Text(convertTimeStamp['createdTimeStamp'])//< 1 second : "Just now" up to < 730 days : "1 year"
Here you can check the format of the output that is going to be displayed: Formats
Timestamp has [toDate] method then you can use it directly as an DateTime.
timestamp.toDate();
// return DateTime object
Also there is an stupid way if you want really convert it:
DateTime.parse(timestamp.toDate().toString())
Long num format date into Calender format from:
var responseDate = 1637996744;
var date = DateTime.fromMillisecondsSinceEpoch(responseDate);
//to format date into different types to display;
// sample format: MM/dd/yyyy : 11/27/2021
var dateFormatted = DateFormat('MM/dd/yyyy').format(date);
// sample format: dd/MM/yyy : 27/11/2021
var dateFormatted = DateFormat('dd/MM/yyyy').format(date);
// sample format: dd/MMM/yyyy : 27/Nov/2021
var dateFormatted = DateFormat('dd/MMM/yyyy').format(date);
// sample format: dd/MMMM/yyyy : 27/November/2021
var dateFormatted = DateFormat('dd/MMMM/yyyy').format(date);
print("Date After Format = $dateFormatted");
Assuming you have a class
class Dtime {
int dt;
Dtime(this.dt);
String formatYMED() {
var date = DateTime.fromMillisecondsSinceEpoch(this.dt);
var formattedDate = DateFormat.yMMMMEEEEd().format(date);
return formattedDate;
}
String formatHMA() {
var time = DateTime.fromMillisecondsSinceEpoch(this.dt * 1000);
final timeFormat = DateFormat('h:mm a', 'en_US').format(time);
return timeFormat;
}
I am a beginner though, I hope that works.
There are different ways this can be achieved based on different scenario, see which of the following code fits your scenario.
Conversion of Firebase timestamp to DateTime:
document['timeStamp'].toDate()
(document["timeStamp"] as Timestamp).toDate()
DateTime.fromMillisecondsSinceEpoch(document['timeStamp'].millisecondsSinceEpoch);
Timestamp.fromMillisecondsSinceEpoch(document['timeStamp'].millisecondsSinceEpoch).toDate();
If timeStamp is in microseconds use:
DateTime.fromMicrosecondsSinceEpoch(timestamp * 1000000);
If timeStamp is in milliseconds use:
DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
Add the following function in your dart file.
String formatTimestamp(Timestamp timestamp) {
var format = new DateFormat('yyyy-MM-dd'); // <- use skeleton here
return format.format(timestamp.toDate());
}
call it as formatTimestamp(document['timestamp'])

Set format of cells produced by LoadFromCollection (epplus) using data annotation

I am using eeplus to create an excel spreadsheet, like this
using (var pck = new ExcelPackage())
{
var ws = pck.Workbook.Worksheets.Add("Customers");
ws.Cells["A1"].LoadFromCollection(customers, PrintHeaders: true);
var ms = new System.IO.MemoryStream();
pck.SaveAs(ms);
ms.WriteTo(Response.OutputStream);
}
The customer class has properties like
[DisplayName("Customer creation date")]
public DateTime Created { get; set; }
DisplayName seems to get honored, so the topmost line will read Customer creation date but the cell contents show up as 43257,41667.
What I would really like to have is cells that has the format 2018-04-05.
Can I do that will data annotations? I tried both
[DisplayName("Customer creation date")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime Created { get; set; }
and
[DisplayName("Customer creation date")]
[DataType(DataType.Date)]
public DateTime Created { get; set; }
but the cell contents remains the same.
No, EPPlus doesnot format your data according to data annotations.
It formats date as integers, so you should specify the column you wish to format as
ws.Column(colPosition+1).Style.Number.Format="yyyy-mm-dd";
You can find details here:
https://github.com/JanKallman/EPPlus/wiki/Formatting-and-styling
https://codereview.stackexchange.com/questions/139569/ensuring-specific-columns-in-an-excelworksheet-format-as-shortdate
EPPlus always changed column name while updating into excel based upon DisplayName Attribute else if there is no DisplayName Attribute is set, then it will Find "_" (underscore) character & replace it with " " (Space) Character in the column name, Due to which we cannot easily find PropertyInfo with help of column name to format the column as per our need.
Here is the simple & quickest solution to format column based upon indexing the PropertyInfo
PropertyInfo[] props = typeof(T).GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
for (int i = 0; i < props.Length; i++)
{
Type t = props[i].PropertyType;
if (t == typeof(DateTime) || t == typeof(DateTime?))
ws.Column(i + 1).Style.Numberformat.Format = "dd-MMM-yyyy HH:mm:ss";
else if (t == typeof(TimeSpan) || t == typeof(TimeSpan?))
ws.Column(i + 1).Style.Numberformat.Format = "HH:mm:ss";
}
I have another solution if you need to format columns based upon column names.
void ApplyDateTimeFormatting<T>(ExcelWorksheet ws, IEnumerable<T> data)
{
if (data.Count() == 0)
return;
Type type = data.First().GetType();
for (int c = 1; c <= toColumns; c++)
{
string column = ws.Cells[1, c].Text;
var t = type.GetPropertyWithDisplayName<T>(column).PropertyType;
if (t == typeof(DateTime) || t == typeof(DateTime?))
ws.Column(c).Style.Numberformat.Format = "dd-MMM-yyyy HH:mm:ss";
else if (t == typeof(TimeSpan) || t == typeof(TimeSpan?))
ws.Column(c).Style.Numberformat.Format = "HH:mm:ss";
}
}
PropertyInfo GetPropertyFromDisplayName(Type type, string DisplayName)
{
MemberInfo[] members = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var member in members)
{
DisplayNameAttribute displayNameAttribute = member
.GetCustomAttributes(typeof(DisplayNameAttribute), inherit: false)
.FirstOrDefault() as DisplayNameAttribute;
string text = ((displayNameAttribute == null) ? member.Name.Replace('_', ' ') :
displayNameAttribute.DisplayName);
if (text == DisplayName)
return type.GetProperty(member.Name);
}
return null;
}
I solved it as follows, so I just load the model and change as per my model if it is int or datetime
var li = typeof(Model).GetProperties().ToArray();
using (var package = new ExcelPackage(stream))
{
var workSheet = package.Workbook.Worksheets.Add("Sheet1");
var i = 0;
foreach (var c in li)
{
i++;
if(c.PropertyType.Name == typeof(DateTime).Name || c.PropertyType.Name == typeof(DateTime?).Name)
workSheet.Column(i).Style.Numberformat.Format = DateTimeFormatInfo.CurrentInfo.ShortDatePattern; ;
if (c.PropertyType.Name == typeof(int).Name || c.PropertyType.Name == typeof(int?).Name)
workSheet.Column(i).Style.Numberformat.Format = "0";
}
}

splitting date/time field to separate date and time

I have a date/time field (i.e. 2018-04-24 10:00:00) that I want to split into separate date and time. I have the following functions, but it does not work with uib-datepicker since I'm splitting a date/time field like a string:
function returnDate(date) {
var apptDate = date.split(' ')[0];
return apptDate;
}
function returnTime(date) {
var apptTime = date.split(' ')[1].substring(0,5);
var hours24 = parseInt(apptTime.substring(0, 2),10);
var hours = ((hours24 + 11) % 12) + 1;
var amPm = hours24 > 11 ? 'pm' : 'am';
var minutes = apptTime.substring(2);
return hours + minutes + ' ' + amPm;
}
I've also tried to use getDate, getFullYear, getMonth, etc. but I keep getting a TypeError with getDate.
Can someone provide some guidance on this date issue? Thanks!
Because between date and time it has a space, so you can get date and time separately by this way.
Method 1 : Split string
string date_time = "2018-04-24 10:00:00";
string[] words = date_time.Split(' ');//Split string
string date = words[0];//date = 1st object (before space)
string time = words[1];//time= 2nd object (after space)
Method 2 : Using Regular expression
string date_time = "2018-04-24 10:00:00";
string _date = "";
string _time = "";
Regex date = new Regex(#"([0-9-]+)\s");
Match match_date = date.Match(date_time);
Regex time = new Regex(#"\s([0-9:]+)");
Match match_time = time.Match(date_time);
//Date
if (match_date.Success)
{
_date = match_date.Value;
Console.WriteLine(_date);
}
//Time
if (match_time.Success)
{
_time = match_time.Value.Replace(" ","");
Console.WriteLine(_time);
}
have you tried new Date('2018-04-24 10:00:00') and then geting month year etc afterwords from a date object?

NULL value is sent to Controller while updating datetime rendered using SetEditItemTemplateContent from GridView Editor Form

DevExpress 17.1
I am having a DateTime column in GridView which displays datetime as MM/dd/yyyy hh:mm:ss.
I have used SetEditItemTemplateContent to have the DateEdit control in EditorForm for updating the DateTime field.
settings.Columns.Add(column =>
{
column.FieldName = "C_DateTime";
column.Caption = "C_DateTime";
column.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
column.PropertiesEdit.DisplayFormatString = "dd/MM/yyyy hh:mm:ss";
column.SetEditItemTemplateContent(c =>
{
var workDate = (DateTime?)DataBinder.Eval(c.DataItem, "C_DateTime");
Html.DevExpress().DateEdit(
dateEdit =>
{
var keyValue = c.KeyValue == null? 0 : c.KeyValue;
dateEdit.Name = "C_DateTime" + keyValue.ToString();
dateEdit.Properties.UseMaskBehavior = true;
dateEdit.Properties.EditFormat = EditFormat.Custom;
dateEdit.Properties.EditFormatString = "dd/MM/yyyy hh:mm tt";
dateEdit.Properties.TimeSectionProperties.Visible = true;
dateEdit.Properties.TimeSectionProperties.TimeEditProperties.EditFormat = EditFormat.Custom;
dateEdit.Properties.TimeSectionProperties.TimeEditProperties.EditFormatString = "hh:mm tt";
dateEdit.Date = DateTime.Now;
}
).Bind(workDate).Render();
});
});
When I changed the datetime value in EditorForm and click Update button, NULL value is sent to the controller instead of the modified datetime value.
Please suggest a way to fix this issue.
Specify the editor's Name according to the bound Model's property:
Html.DevExpress().DateEdit(dateEdit => {
//var keyValue = c.KeyValue == null? 0 : c.KeyValue;
//dateEdit.Name = "C_DateTime" + keyValue.ToString();
dateEdit.Name = "C_DateTime";
...
//or
dateEdit.Name = column.FieldName;
}).Bind(workDate).Render();
Note that you can add the necessary settings via the column.PropertiesEdit().DateEdit settings (without using the SetEditItemTemplateContent method).

Resources