Parsing DateTime in a Model - c#

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.

Related

ToString() method not working in Modle's Getter/Setter

I have a C# Model that contains a birthday. The birthday field takes the birthday from a separate API in the DateTime format. I've been trying to change this to a String instead, and I want to do it with Getters/Setters, if possible.
I get an error for ToString() when trying to do this. Error states "cannot convert from "string" to "System.IFormatProvider". I've tried lots of other variants of this and I just can not get something to work. I want to be able to achieve it via the Getters/Setters.
public class PersonLookUpModel
{
public DateTime? DateOfBirth { get; set; }
public string? _dateOfBirthString;
public string? DateOfBirthString {
get => DateOfBirth;
set => _dateOfBirthString = value.ToString("MMMM dd"); }
}
Here you go.
public class PersonLookupModel
{
public DateTime DateOfBirth{get;set;}
public string DOBString => DateOfBirth.ToString("MMM dd");
}
This is what ended up working:
public DateTime? DateOfBirth { get; set; }
public string _dobString;
public string DOBString {
get => _dobString = DateOfBirth?.ToString("MMMM dd");
set => _dobString = value; }

How to add a date and time to a PostgreSQL database with EF?

I have a data model, with the help of EF migration I created a data table based on this model.
public class Event
{
public int Id { get; set; }
public string Theme { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public string Place { get; set; } = string.Empty;
}
After that, I remembered that I forgot to add the date and time field. I added this field and created a new migration, after which I applied the update database command.
public class Event
{
public int Id { get; set; }
public string Theme { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public DateTime EventTime { get; set; }
public string Place { get; set; } = string.Empty;
}
When executing my request to update the date and time via the Web Api, I get the following error:
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details. ---> System.InvalidCastException: Cannot write DateTime with Kind=Unspecified to PostgreSQL type 'timestamp with time zone', only UTC is supported. Note that it's not possible to mix DateTimes with different Kinds in an array/range. See the Npgsql.EnableLegacyTimestampBehavior AppContext switch to enable legacy behavior.
When executing my request to update the date and time via the Web Api, I get the following error. Before adding the date and time field, everything worked fine, with MSSQL everything also works fine and the date is added well.
Cannot write DateTime with Kind=Unspecified to PostgreSQL type 'timestamp with time zone', only UTC is supported
That means you need to convert your EventTime to UTC

Translate ISO 8601 UTC time format to hh:mm of EST

I have a list of objects that I de-serialized from a json string that have a start/end time field expressed in UTC time. Eg: "2016-08-22T15:30:00Z" (which is 11:30AM EST). I need to transform the time to a user-friendly format (e.g, "11:30 AM") on the server before sending down the list in JSON for displaying on a web page. Is there a c# function that will help me accomplish this transform the time property to the desired result?
code example:
public class Event
{
public int EventId { get; set; } //1
public string Name { get; set; } //Karate class
public string StartAt { get; set; } //2016-08-22T15:30:00Z
public string EndAt { get; set; } //2016-08-22T16:30:00Z
}
public class Events
{
public List<Event> Events {get; set;}
}
//de-serialize from json string
string eventsForToday = "{}" //some json string from api
var eventList = (Events)JsonConvert.DeserializeObject(eventsForToday, typeof(Events));
foreach (var item in eventList.Events)
{
//needs to be 11:30AM instead of 2016-08-22T15:30:00Z
Console.WriteLine (item.StartAt)
}
I know that the logic is whatever the UTC time is it should be offset by 4 (or 5 depending on time of year). But what is the most straight-forward way to modify the objects? Is there a way to project a new list with the format changed, etc?
You can convert each string into a DateTime. DateTime has a method ToLocalTime() that will do the conversion for you as long as you specify the Kind property of the DateTime. For example,
foreach (var item in eventList.Events)
{
DateTime timeUtc = DateTime.SpecifyKind(DateTime.Parse(item.StartAt), DateTimeKind.Utc);
Console.WriteLine (timeUtc.ToLocalTime()); //Add .ToShortTimeString() if you just want the time (and not the date)
}
However, since your string has a trailing "Z", you should just be able to use Convert.ToDateTime(item.StartAt).ToWhateverString()

Different timestamp retrieval from mongodb after inserting from C#

I'm working with MongoDB, and found weird behaviour (at least for me). I got time difference when inserting from C# and retrieve it from MongoDB.
My entity :
[BsonId]
public ObjectId Id { get; set; }
public bool IsActive { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedTime { get; set; }
public string Name { get; set; }
Timestamp was inserted using below code :
public bool Insert(AccountCategories _input)
{
_input = new AccountCategories();
_input.CreatedBy = "super-admin";
_input.CreatedTime = DateTime.Now;
_input.Id = new ObjectId();
_input.IsActive = true;
_input.Name = "test-name";
var _result = _repo.Insert(_input);
return _result;
}
Inserted data : {4/30/16 9:04:36 PM}
Retrieval data : {4/30/16 2:04:36 PM}
I have tried to modify the entities by adding Bson attribute, but it was not working:
[BsonRepresentation(BsonType.Document)]
public DateTime CreatedTime { get; set; }
Why this behaviour happened ? and how can I fix this ?
I managed to found the answer after changing my keyword during search on this site and google.
According to MongoDB manual :
https://docs.mongodb.org/manual/tutorial/model-time-data/
Time is defaulted to UTC, that's why I got 7 hours difference (my bad to not look into the manual first)
So I managed to fix my problem by adding BsonAttribute to the Datetime as below :
[BsonDateTimeOptions(Kind=DateTimeKind.Local)]
public DateTime CreatedTime { get; set; }
source : Dealing with how MongoDB stores DateTime when used with Service Locator Pattern

User Defined Class list error "Failed to compare two elements in the array"

I have some code that takes a list made up of custom class objects (called Payments) and sorts them by date, as below:
payments.Sort(delegate(Payments p1, Payments p2) { return p1.GetDate().CompareTo(p2.GetDate()); });
the GetDate() method and the payment class is below:
public class Payments
{
public string Date { get; set; }
public string Payment { get; set; }
public string Reference { get; set; }
public decimal Amount { get; set; }
public DateTime GetDate()
{
return DateTime.Parse(this.Date);
}
}
Once the list is sorted I manually go through each one and compare the date on it to the date on the next one. If they are different then nothing happens, if they are the same then I merge the data in the Payments together into a single new Payment. I then remove the two payments that were being compared and then add in the new one, the list is then resorted and continued until the list is unique by date.
Up until very recently this has been working fine, with no issues. However from today there have been multiple cases of it erroring with the message "Failed to compare two elements in the array".
I have looked around for this but I dont feel that i know enough about what could be causing it to comfortably make changes to my code. Can someone help me understand what would be causing this issue and the best way to fix it?
Thanks
When using Sort, the class of the parameters must implement IComparable interface.
public class Payments : IComparable<Payments>
{
public string Date { get; set; }
public string Payment { get; set; }
public string Reference { get; set; }
public decimal Amount { get; set; }
public int CompareTo(Payments otherPayment)
{
return DateTime.Parse(this.Date).ComapreTo(DateTime.Parse(otherPayment.Date));
}
}

Categories

Resources