Hi i am trying to create a date in c# without the time at the end of it just the date. So i am using DateTime.date. I am still getting the time at the end though when i write it out to console not sure why. I am writing date out to console in a class i call Buisnesslogic but nothing happens with date between that i convert it correctly and write it out to console. Here is my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
namespace Miniproject_2021_09_22
{
class Asset
{
public string assetName { get; set; }
public string date { get; set; }
public double price { get; set; }
public string office { get; set; }
public string currency { get; set; }
public DateTime purchaseDate;
public Asset(string assetName, string date, double price, string office)
{
this.assetName = assetName;
this.date = date;
this.price = price;
this.office = office;
}
public virtual string getAssetType()
{
return "Asset";
}
public Asset convertPrice()
{
if (office.ToLower().Trim() == "sweden")
{
currency = "Sek";
return this;
} else if (office.ToLower().Trim() == "usa")
{
price = price / 8.63;
currency = "$";
return this;
} else if (office.ToLower().Trim() == "portugal")
{
price = price / 10.14;
currency = "£";
return this;
}
else
{
currency = "Sek";
return this;
}
}
public void createDate()
{
string pattern = "MM-dd-yy";
bool isValidDate = DateTime.TryParseExact(date, pattern, null, DateTimeStyles.None, out purchaseDate);
while (!isValidDate)
{
Console.Write("The date you entered is in wrong format please enter a date that follows this format MM-dd-yy: ");
isValidDate = DateTime.TryParseExact(Console.ReadLine(), pattern, null, DateTimeStyles.None, out purchaseDate);
}
date = purchaseDate.Date.ToString();
}
}
}
CodePudding user response:
You can use ToShortDateString
like this:
using System;
public class Program
{
public static void Main()
{
Console.WriteLine(DateTime.Now.ToShortDateString());
}
}
The problem you are seeing is that DateTime.Now.Date
gives you a DateTime
initialized to the current date with 12:00:00 AM
as the time. If you then run ToString
it still shows both the date and the time.
See the docs for more info, especially if you want to change the culture that is used to format the string.