IComparable sorting with DateTime - c#

I had a similar question answered earlier, then my boss told me to sort it based on date so here I am again.
I have this -
List<User> users;
protected class User : IComparable<User>
{
public string name;
public string email;
public decimal total;
public string address;
public string company;
public string placed;
public string fulfilled;
public string origin;
public int CompareTo(User b)
{
// Alphabetic sort name[A to Z]
return this.placed.CompareTo(b.placed);
}
}
My datetime format is MM/DD/YYYY, so it goes by the month, not by the whole thing. What's the best way to get it to sort based on the full date? Thanks!

You know it is a date, then why store it as string? use dedicated DateTime type. It will work as expected.
If you can't change the field to DateTime for some reason, you can always do the following
public int CompareTo(User b)
{
DateTime x = DateTime.ParseExact(this.placed,...);
DateTime y = DateTime.ParseExact(b.placed,...);
return x.CompareTo(y);
}

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; }

Using setter in ViewModel using another property

I have the following ViewModel in my app and there is two BirthDate property (with / without time). When using set { } without body I encounter "Not using the value means that the accessor ignores the caller's intent which could cause unexpected results at runtime.". Then I added a private property and update set as set { birthDateWithTime = value; }. However, this time birthDateWithTime private property not sees to be used. Is there any mistake regarding to implementation below? I want to use both property separately and do not want to convert in JavaScript or code.
public class DemoViewModel
{
public int Id { get; set; }
public DateTime BirthDate { get; set; }
private string birthDateWithTime;
public string BirthDateWithTime {
get { return BirthDate.ToString("dd/MM/yyyy - HH:mm"); }
set { birthDateWithTime = value; }
}
}
#Gabriel Llorico answer is correct. or maybe you can try another one.
private DateTime _birthDate;
public DateTime BirthDate{
get{
return _birthDate;
}
set{
this._birthDate = value;
this.BirthDateWithTime = this._birthDate.ToString("dd/MM/yyyy - HH:mm");
}
}
public string BirthDateWithTime{get;set;}
try this if it is solely dependent on BirthDate
public string BirthDateWithTime
{
get
{
return BirthDate.ToString("dd/MM/yyyy - HH:mm");
}
}
Or just use a body-property style.
public string BirthDateWithTime => BirthDate.ToString("dd/MM/yyyy - HH:mm");
If you need to set BirthDateWithTime, just set in the BirthDate property, so both are updated.

convert my type to string

I have a class as:
public class PersianDate
{
public int Year;
public int Month;
public int Day;
public int Hour;
public int Minute;
public int Second;
public string MonthName;
}
I want that if I convert it like here:
HTools.PersianDate pDate=new HTools.PersianDate();
string date = pDate.ToString();
And I want date to be:
1396-06-14T19:17:38
How can I do that?
public class PersianDate
{
public int Year;
public int Month;
public int Day;
public int Hour;
public int Minute;
public int Second;
public string MonthName;
public override string ToString()
{
return string.Format("{0}-{1}-{2}T{3}:{4}:{5}",Year,Month,Day,Hour,Minute,Second);
}
}
Override ToString() method from object class to get the format you want.
DotNetFiddle Example.
If you want a string that represent the object as a json you can use the "Newtonsift.Json" Nuget package:
PersianDate thing = new PersianDate();
//TODO: fill you thing with the data you need
string json = JsonConvert.SerializeObject(thing);
If you want specific string - ovverride the ToString methods in your class:
public override string ToString()
{
return $"{Year}-{Month}-{Day}T{Hour}:{Minute}:{Second}";
}

Class List Keeps Printing Out As Class Name In Console?

Ok, so maybe I'm just tired or something but I can't seem to figure out why this keeps happening.
The code below is called every day for a data point in a database I have.
When I print to the console for debugging, it simply prints out as:
NamespaceName.SharePrices
Not sure what is going on.
public void OnData(TradeBars data)
{
decimal price = data["IBM"].Price;
DateTime today = data["IBM"].Time;
//--------------Below works fine.
if (today.Date >= nextTradeDate.Date)
{
MarketOnOpenOrder("IBM", 50);
Debug("Purchased Stock");
nextTradeDate = today.AddDays(1);
MarketOnOpenOrder("IBM", -25);
}
var derpList = new SharePrices { theDate = today, sharePrice = price };
List<SharePrices> newList = new List<SharePrices>();
newList.Add(derpList);
newList.ForEach(Console.WriteLine);
}
}
public class SharePrices
{
public DateTime theDate { get; set; }
public decimal sharePrice { get; set; }
}
Please excuse my naming conventions. This is just a wireframe for a personal project.
//----------Edit
Thanks for the help guys. I guess what I wasn't understanding is why it was working in my TestClass I wrote just playing with fake data, and when the real implementation came it didn't work:
public static void FindWindowDays()
{
DateTime currentDate = DateTime.Now;
var dates = new List<DateTime>();
for (var dt = currentDate.AddDays(-windowDays); dt <= currentDate; dt = dt.AddDays(1))
{
dates.Add(dt);
}
var ascending = dates.OrderByDescending(i => i);
foreach (var datesyo in ascending)
{
Console.WriteLine(datesyo);
}
}
This seemed to work fine printing the DateTime to console without converting to string. But when I added the second element, it stopped working. That's where I got confuddled.
C# doesn't know anything about the SharePrices other than the class name. If you want it to display something specific, you will need to override the ToString() method like so:
public override string ToString()
{
return "SharePrice: " + theDate.ToString() + ": " + sharePrice.ToString();
}
Of course, you can format it however you like, that is the beauty of it. If you only care about the price and not the date, only return the sharePrice.
You should override ToString() for your class in format as you want, for example like this:
public class SharePrices
{
public DateTime theDate { get; set; }
public decimal sharePrice { get; set; }
public override string ToString()
{
return String.Format("The Date: {0}; Share Price: {1};", theDate, sharePrice);
}
}
By default, without overriding, ToString() returns a string that represents the current object. So that's why you get what you described.
When you call Console.WriteLine on a class, it will call the ToString() method on that class automatically.
If you want to print the details out, you will over need to override ToString() in your class, or call Console.WriteLine with each property you want to print out.
this will work without having to use .ToString()
public class SharePrices
{
public DateTime theDate { get; set; }
public decimal sharePrice { get; set; }
}
SharePrices sp = new SharePrices() { theDate = DateTime.Now, sharePrice = 10 };
var newList2 = new List<SharePrices>();
newList2.Add(sp);
newList2.ForEach(itemX => Console.WriteLine("Date: {0} Sharprice: {1}",sp.theDate, sp.sharePrice));

Calculate years in a POCO Calculated Property

I'm assuming I'm pretty close. I have a value StartedAgent that will contain a specific date entered by the user. Lets say they entered "1/1/1985" I then want to create a calculated property that I can use to display how many years since this agent first started working in Real Estate. Below is my class. I have tried to take a stab at it, but I'm coming up short. I'm using MVC 5, EF 6 & .Net 4.5 in the flavor of C#.
namespace OrlandoAppraiser.Models
{
public class Appraiser
{
public int AgentID { get; set; }
public string Name { get; set; }
public string LicenseNum { get; set; }
public DateTime StartedAgent { get; set; }
public string YearsAsAgent
{
get { return (Math.Floor((DateTime.Now - StartedRealEstate).TotalDays / 365.25D)); }
}
}
}
I have looked at some different answers, but I'm having trouble finding a way of doing this simple inside a calculated property. I know it shouldn't be that much different, but I'm getting errors with my code.
This is a pretty simplistic approach. Make sure you call ToString() if the property is a string.
public string YearsAsAgent
{
get { return (DateTime.Now.Year - StartedRealEstate.Year).ToString(); }
}
This should help. Modified version of this.
DateTime _startedRealEstate = new DateTime(2012, 11, 15);
public DateTime StartedRealEstate { get { return _startedRealEstate; } set { _startedRealEstate = value; } }
public int YearsAsAgent
{
get
{
DateTime zeroTime = new DateTime(1, 1, 1);
TimeSpan span = DateTime.Now - StartedRealEstate;
int years = (zeroTime + span).Year - 1;
return years;
}
}
private void button1_Click_2(object sender, EventArgs e)
{
int totalYears = YearsAsAgent;
}

Categories

Resources