Dataset value Convert DateTime to Date
foreach (DataRow dr in dataSet.Tables[0].Rows)
{
dr["JoinDate"] = DateTime.Parse((dr["JoinDate"].ToString())).ToShortDateString();
dataSet.Tables[0].Rows[0]["JoinDate"] = dr["JoinDate"];
}
I assume that you want to get the Date part alone form Datetime from your question (datetime is should change to only date in dataset)
foreach (DataRow dr in dataSet.Tables[0].Rows)
{
dr["JoinDate"] = DateTime.Parse((dr["JoinDate"].ToString())).Date
dataSet.Tables[0].Rows[0]["JoinDate"] = dr["JoinDate"];
}
Datetime.Date will give you the date value.
refer this : How to remove time portion of date in C# in DateTime object only?
Try this
foreach (DataRow dr in dataSet.Tables[0].Rows)
{
dr["JoinDate"] = dr["JoinDate"].ToString("dd/MM/yyyy");
dataSet.Tables[0].Rows[0]["JoinDate"] = dr["JoinDate"];
}
Related
I have written a code that subtracts 2 DateTime properties and gives AHT for that task. AHT shows as follows 00:00:00:567, but how can display this as hh:mm:ss format.
Kindly help with this, help is very much appreciated
Below is my Action created.
using(Db db = new Db())
{
Chat newDTO = db.Chats.Where(x => x.ChatId == id).FirstOrDefault();
DateTime startTime = Convert.ToDateTime(newDTO.FeedbackDateTime);
DateTime endtime = Convert.ToDateTime(newDTO.FeedbackSharedDateTime);
TimeSpan duration = endtime.Subtract(startTime);
//hh:mm:ss
string stringAHT = string.Format("{0:D2}:{1:D2}:{2:D2}:{3:D2}",
24 * duration.Days + duration.Hours,
duration.Minutes,
duration.Seconds,
duration.Milliseconds
);
newDTO.AuditorAHT = stringAHT;
db.SaveChanges();
}
Thank you in advance.
Finally made it work
Created AuditorAht field as string data type
In Controller:
string aht = string.Format("0:hh\\:mm\\:ss", dto.datetime1 - dto.datetime2);
dto.AuditorAht = aht;
db.Savechanges();
Now Average Time is storing as hh:mm:ss format as I wanted it to.
The following method should delete all old data however, when I did my investigation I found out that some of the data in the database was not delete even though the posted date was within the range. Can someone explain why?
Data That did not get deleted:
19/02/2020
01/04/2020
24/03/2020
public ActionResult DeleteOldData()
{
for(int i = 8; i < 900; i++)
{
DateTime now = DateTime.Now;
var time = now.AddDays(-i).ToString("dd/MM/yyyy").ToString();
db.Data.RemoveRange(db.Data.Where(a => a.PostedDate == time).ToList());
db.SaveChanges();
}
return View();
}
The preferrable comparison operator for this one is just comparing the 2 dates with <= but the dilemma is you're storing the date as a string, hence we can't compare it directly using LINQ, need to do a workaround like below;
Try the code below, try it also without the loop;
DateTime now = DateTime.Now;
var time = now.AddDays(-i).ToString("dd/MM/yyyy").ToString();
var dateList = db.Data.ToList();
List<Data> toDelete = new List<Data>();
foreach(var item in dateList){
if(Convert.ToDateTime(a.PostedDate) <= Convert.ToDateTime(time)){
toDelete.Add(item);
}
}
db.Data.RemoveRange(toDelete);
db.SaveChanges();
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";
}
}
I need to get the number of days between two dates from database using Linq Query, please help me how to do this. thanks
I tried the bellow code but it return me the result nul! please help
DateTime rightNow = DateTime.Now;
//int totalDays = (from d in db.vuExpiredProjectsAssigned
// where d.AssignedTo==obj.DepartmentID
// select (d.AssignedDate - d.DueDate).Days).FirstOrDefault();
//var numberdays = (from pd in db.vuExpiredProjectsAssigned
// where pd.AssignedTo == obj.DepartmentID
// select SqlFunctions.DateDiff("day", pd.AssignedDate, rightNow));
var result =(from dd in db.vuExpiredProjectsAssigned
where dd.AssignedTo==obj.DepartmentID
select new
{
days=SqlFunctions.DateDiff("Day",dd.DueDate,rightNow)
});
ViewBag.ndays = result;
Arithmetic with DateTime is not supported in Entity Framework. You have to use DbFunctions*. So, for the first part of your statement, something like:
var numberdays = ( from p in db.vuExpiredProjectsAssigned
where p.AssignedTo == obj.DepartmentID
select DbFunctions.DiffDays(p.AssignedDate,p.DueDate));
OR
var numberdays = ( from p in db.vuExpiredProjectsAssigned
where p.AssignedTo == obj.DepartmentID
select SqlFunctions.DateDiff("day", p.AssignedDate, p.DueDate));
For more reference please check below links.
SqlFunctions Class
DbFunctions Class
try with this
DbFunctions.DiffDays(dd.DueDate,rightNow).Value
Update
var rightNow= DateTime.Today.ToShortDateString();
public class democlass
{
public int count {get; set;}
}
and query like this
var result =(from dd in db.vuExpiredProjectsAssigned
where dd.AssignedTo==obj.DepartmentID
select new democlass()
{
count = DbFunctions.DiffDays(dd.DueDate,rightNow).Value
});
then check your result variable.
As long as you are not using the difference in days in the where clasuse, then it is better to do this calculation in your code instead of adding overhead to SQL, so change your code to:
public class democlass
{
public DateTime DueDate{get;set;}
public int count {get; set;}
}
var result =((from dd in db.vuExpiredProjectsAssigned
where dd.AssignedTo==obj.DepartmentID
select new democlass()
{
DueDate= dd.DueDate;
})).ToList();
result.ForEach(a=> {a.count = a.DueDate.Subtract(DateTime.Now).TotalDays});
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)