I am trying to display the time in a gridview column but when loading the information I get this error:
Specified cast is not valid.
protected override void FillObject(DataRow dr)
{
ID = Convert.ToInt32(dr["ID"]);
if (dr["Company_ID"] != DBNull.Value)
CompanyID = Convert.ToInt32(dr["Company_ID"]);
if (dr["LoginTime"] != DBNull.Value)
LoginTime = (TimeSpan)(dr["LoginTime"]); //error
}
Get/Set code:
public TimeSpan LoginTime { get; set; }
As #TimS. pointed out, you need to use a DateTime variable in your code to consume a Sql Server DATETIME. From that, you can convert it into a TimeSpan if necessary.
public DateTime LoginTime { get; set; }
LoginTime = (DateTime)(dr["LoginTime"]);
To convert between the two, see How to get TimeSpan from DateTime
Related
I'm trying to create a filter and find records by a date range. The thing is, the dates in our mongo server are (sadly, its historically like this and was imported from another database) stored as string type, in the format of "dd/MM/yyyy hh:mm:ss". How can I filter from user input dates? No matter what I've tried I got wrong results.
Here's some code:
[Serializable]
public class Error
{
[BsonElement("projectName")]
public string projectName { get; set; }
[BsonElement("programName")]
public string programName { get; set; }
[BsonElement("errorDescription")]
public string errorDescription { get; set; }
[BsonElement("userDescription")]
public string userDescription { get; set; }
[BsonElement("logDateTime")]
[BsonSerializer(typeof(DateSerializer))]
public DateTime logDateTime { get; set; }
[BsonElement("writeDateTime")]
public string writeDateTime { get; set; }
}
And here's the DateSerializer:
public class DateSerializer: SerializerBase<DateTime>
{
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, DateTime value)
{
context.Writer.WriteString(value.ToString(CultureInfo.InvariantCulture));
}
public override DateTime Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
var dateText = context.Reader.ReadString();
return convertToDate(dateText);
}
private DateTime convertToDate(string dateText)
{
CultureInfo ci = new CultureInfo(CultureInfo.CurrentCulture.Name);
ci.DateTimeFormat.ShortDatePattern = "dd'/'MM'/'yyyy";
ci.DateTimeFormat.LongTimePattern = "hh':'mm tt";
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
string format = "dd/MM/yyyy HH:mm:ss";
DateTime dateTime = DateTime.ParseExact(dateText, format, ci);
return dateTime;
}
}
on my filter:
DateTime dateTime2 = DateTime.ParseExact(date, format, ci);
var fromDateFilter = builder.Gte(x => x.error.logDateTime, dateTime2);
and eventually:
filter = filter & fromDateFilter;
var results = errorCollection.Find(filter).ToList();
I've tried many different ways but can't seem to get the comparison to work properly.
Edit: I only care about the dates. The time is not very important.
Edit 2 - Apparently it only compares the day, for example it returns that 01/06/2017 (dd/mm/yyyy) is smaller than 06/02/2017 (dd/mm/yyyy). This is also true for 02-05/06/2017 until 06/06/2017.
I have an employee model:
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
...
public DateTime TerminationDate{ get; set; }
}
The model is populated automatically (by HttpResponseMessage's Content.ReadAsAsync<Employee>())
The default value for TerminationDate (when the employee is still with the company) is 0000-00-00, which can't be converted to a DateTime object, presumably because there is not 0th day or month. I get the error:
Could not convert string to DateTime: 0000-00-00. Path 'terminationDate', line 1, position 533.
The default date value can't be changed - I'm getting that from a 3rd party service.
The only workaround that I can think of is to set the TerminationDate to be a string, but then everything that gets the TerminationDate will have to parse it into a DateTime object.
Is there anything more elegant that I could do?
I would suggest making the termination date to be nullable.
public DateTime? TerminationDate{ get; set; }
Since current employees don't have a TerminationDate, it would be reasonable to leave it as null.
I'm facing an issue with date formatting. Upon calling up the UpdateItem action, the date format for CreatedAt gets messed up. I'm using JSON by the way, so must be something to do with date serialization.
Model:
public class Item
{
public int ItemId { get; set; }
public string ItemName { get; set; }
public string CreatedBy { get; set; }
public DateTime? CreatedAt { get; set; }
public string UpdatedBy { get; set; }
public DateTime? UpdatedAt { get; set; }
}
Create action:
public int CreateItem(Item item)
{
var item = new Item();
viewModel.CopyToItem(item);
item.CreatedBy = WebSecurity.CurrentUserName;
item.CreatedAt = DateTime.Now;
db.Items.Add(item);
db.SaveChanges();
return item.ItemId;
}
Update action:
public void UpdateItem(Item item)
{
item.UpdatedBy = WebSecurity.CurrentUserName;
item.UpdatedAt = DateTime.Now;
db.SaveChanges();
}
The incorrect date format:
/Date(1395366469723)/
It should be:
2014-03-21T09:50:01.747
I tried this in the controller but get a String was not recognized as a valid DateTime' error.
string isoJson = JsonConvert.SerializeObject(DateTime.Now, new IsoDateTimeConverter());
item.CreatedAt = DateTime.ParseExact(isoJson, "yyyy-MM-dd hh:mm:ss.ttt", CultureInfo.InvariantCulture);
Using non-nullable DateTime in the model didn't fix it either.
Javascript uses Unix Time. If you are wanting to get a DateTime object with the given javascript date value, create a new DateTime object from 1/1/1970 and then add the milliseconds.
Observe:
var dt = new DateTime(1970, 1, 1).AddMilliseconds(1395366469723);
// "21/03/2014 1:47:49 AM"
I am using Entity Framework to insert a row of data into my Application table.
Here's the class:
public partial class Application
{
public Application()
{
this.TestAccounts = new List<TestAccount>();
}
public int ApplicationId { get; set; }
public string Name { get; set; }
public byte[] RowVersion { get; set; }
public System.DateTime ModifiedDate { get; set; }
public virtual ICollection<TestAccount> TestAccounts { get; set; }
}
Here's the C# code:
_Uow.Applications.Add(new Application { Name = name });
It's giving me an error saying
InnerException: System.Data.UpdateException
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=System.Data.Entity
InnerException: System.Data.SqlClient.SqlException
HResult=-2146232060
Message=The conversion of a datetime2 data type to a datetime data type
resulted in an out-of-range value.
How can I change my C# code to insert the current date in the ModifiedDate field?
You could specify a new constructor
public Application(string Name)
{
if(ModifiedDate == null)
//ModifiedDate = Convert.ToDateTime(01.01.2000);
ModifiedDate = DateTime.Now;
}
OR
public Application(string Name, System.Nullable<DateTime> modifiedDate)
{
if(modifiedDate != null)
//ModifiedDate = Convert.ToDateTime(01.01.2000);
ModifiedDate = DateTime.Now;
else
Do stuff
}
This isn't beatifull, but should do the trick.
Simply that way:
_Uow.Applications.Add(new Application
{
Name = name,
ModifiedDate = DateTime.Now
});
Or you may do it in the constructor:
public class Application
{
public Application()
{
ModifiedDate = DateTime.Now;
}
}
By the way: You got the exception because per default c# DateTime is more precise than datetime of SQL. Like the message says: Use datetime2 in SQL. DateTime has it's min value as initial value, which is too low for SQL datetime.
hi your ModifiedDate is initialized with minvalue as a result it gives an exception. Better to use either
public System.DateTime? ModifiedDate { get; set; } to make it nullable or
initialize in the construction
public Application()
{
this.TestAccounts = new List<TestAccount>();
ModifiedDate = DateTime.Now;
}
I kinda confuse about the date time conversion
in my model i have defined
public DateTime? Sent { get; set; }
public DateTime? Reply { get; set; }
public double ResponseTime { get; set; }
in linq part i am using
ResponseTime = (u.Reply - u.sent).TotalMilliseconds
which is not formated and displayed like this 979809803
I want to know how do i convert it to datetime format, and eventually will display the format as hour:minute, for instance 2:45 between the date sent and date reply.
Just return the TimeSpan and call .ToString("hh:mm").
TimeSpan.ToString
public TimeSpan ResponseTime { get; set; }
//usage in LINQ
ResponseTime = (u.Reply - u.Sent)
When displaying...
value.ResponseTime.ToString("hh:mm")
Subtracting a DateTime from a DateTime yields a TimeSpan. Have a look at the TimeSpan.ToString Method (String) to see how you can custom format the value.
You can change ResponseTime back to a TimeSpan and from there to a string.
TimeSpan ResponseTimeSpan = new TimeSpan(0, 0, 0, (int)ResponseTime);
string ResponseTimeDisplay = ResponseTimeSpan.ToString();