DateTime.ToString issue - c#

I try to display a DateTime with the "general date short time" format.
When I use the g specifier, it gives me something like 01-08-13 10:12:00 10:12 instead of 01-05-13 10:12.
It seems to duplicate the time and I don't know why.
Anyone?
Edit 1
Here is the code I use:
var startDate = DateTime.MinValue.ToString("g");
if (Airspace.StartDate != null)
startDate = ((DateTime)Airspace.StartDate).ToString("g"); //01-08-13 00:00:00 00:00
Edit 2
The same issue occurs when I use "short date pattern":
var startDate = DateTime.MinValue.ToString("d");
if (Airspace.StartDate != null)
startDate = ((DateTime)Airspace.StartDate).ToString("d"); //01-08-13 00:00:00
It doesn't make sense!

The "d" format specifier applies the short date pattern and "g" is a concatenation of the short date and short time patterns. So based on your results, you somehow have a short date pattern with time components in it. I can reproduce your results by setting such a short date pattern explicitly, like so:
Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd HH:mm:ss";
Console.WriteLine(DateTime.Today.ToString("g")); // 2008-05-11 00:00:00 00:00
Console.WriteLine(DateTime.Today.ToString("d")); // 2008-05-11 00:00:00
I think the real question is how you ended up with what looks like some very strange culture settings! I tried enumerating the set of supported cultures and looking for one whose short date format included time specifiers, like so:
foreach (var culture in CultureInfo.GetCultures(CultureTypes.AllCultures)
.OrderByDescending(c => c.DateTimeFormat.ShortDatePattern.Length))
{
Console.WriteLine($"{culture.Name} {culture.DateTimeFormat.ShortDatePattern}");
}
But in several hundred cultures I came up with nothing. So, can you find anything anywhere in your code that's building up a CultureInfo object and assigning it as the current culture? If yes, maybe there's a mistake in that code somewhere.

Hope this can help you:
DateTime today = DateTime.Now;
Console.WriteLine(today.ToString("dd-MM-yy H:mm"));
//Result: 01-08-13 04:33
Console.ReadLine();
Other format: http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm

Try this
startDate = DateTime.Now.ToString(System.Globalization.CultureInfo.
CurrentCulture.DateTimeFormat);

Related

Convert DateTime 1/20/2022 8:48:30 PM to 20/01/2022 8:48:30 PM C#

I basically have two DateTime variables
DateTime dateToday = WorldTimeAPI.Instance.GetCurrentDateTime();
DateTime dateFinish;
dateToday gets current date from the web, with this format 1/20/2022 8:48:30 PM.
dateFinish has this other format 20/01/2022 8:48:30 PM, the day first, and then the month, everything else is the same.
I want to be able to parse one of them to match the other one in terms of format so that I can compare them both to know if todays date is greater than date finish by doing this:
if(dateToday.CompareTo(dateToEndMission) > 0)
{do stuff}
I tried looking at documentation but it has so many different formats that I just couldnt figure out the exact way to do it.
To compare two dateTime values in an if statement you can do:
if(firstDate.Date > secondDate.Date)
{
//Do something...
}
Try and keep things as simple as possible.
As stated above you can compare date time with the > operator. But I would go further and ask why you're using that api to get the current date and time when you could just use this
DateTime today = DateTime.Now;
This should fix your problem, because you should be initialising date time in the same way now. If not, then I suggest you take a look at this other questions answers:
Convert DateTime to a specified Format
You can try the ParseExact method
DateTime dateToday = DateTime.Now;
DateTime dateFinish = DateTime.ParseExact("20/01/2022 10:56:09", "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
if (dateToday > dateFinish)
{
// do something
}

DateTime.Parse - changes format

I'll try to illustrate an example:
var dateNow = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
produces: 10/01/2014 21:50:34
var dateNowParse = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
produces: 10/01/2014 9:50:34 PM
QUESTION:
How to parse the date, and keep formatting like: dd/MM/yyyy HH:mm:ss, with an 24 hour format, without any PM
Thank you!
Update 1
Sorry maybe my question wasn't so clear, i'll try to explain the real situation below.
Please do not focus on real meaning of DateTime.Now, suppose we have a string variable in the format of 10/01/2014 21:50:34, and then I try to parse it, and store the result in another variable. What I am willing to achieve is to keep the result in a DateTime variable which has the exact formatting 10/01/2014 21:50:34.
Now here is a snippet:
var stringDate = "10/01/2014 22:50:30";
DateTime parsedDate = DateTime.Parse(stringDate, CultureInfo.InvariantCulture);
//parsedDate result is: 10/01/2014 10:50:30 PM
What is frustrating me is:
In the stringDate the 22:50 hour says that the string is formatted to the 24 hour clock. (the 12 clock format uses hours counter up to 12)
If I used 22:50, Isn't logically that the output should'nt use any AM PM and 12 hour format?
How to parse the date, and keep formatting
You need to keep the format alongside the DateTime if you want to. A DateTime does not have any concept of being in a particular format. The value of the DateTime returned by Parse isn't "10/01/2014 9:50:34 PM" - it's that particular date and time, but not a string representation.
You could have a type which maintains the two together - or if you always want to format in the same way, just specify that format explicitly when you format, without keeping it as data with the DateTime value.
Personally I would try to stick to DateTime.ParseExact where feasible, as I find it easier to predict what it will do - but it does depend on your input. If it's input with a particular format that you're expecting, ParseExact really is the way forward, potentially with the invariant culture to avoid any cultural differences.
I would store the date now as a date
DateTime dateNow = DateTime.Now;
then when you need to display it with that formatting
String strNow = dateNow.ToString("dd/MM/yyyy HH:mm:ss");
If you have a date coming in with a format say in a String variable strNow and want to put it in the DateTime I would make sure to catch format exceptions
DateTime dateNow;
try {
dateNow = DateTime.ParseExact(strNow, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
}
catch (FormatException) {
//Log something or set a default date.
}
DateTime.ParseExact(DateTime, Format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite);
for example:
DateTime.ParseExact(strNow, "dd/MM/yyyy HH:mm:ss", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite);

How to parse string to DateTime?

I have product list and every product has create date in DateTime type. I want to take some products that created after my entering time in string type.
I enter EnteredDate in string type, like this format : 05/16/2012
1. var dates = from d in Products
2. where d.CreateDate >= DateTime.ParseExact( EnteredDate, "mm/dd/yy", null )
3. select d;
In second line I got error as String was not recognized as a valid DateTime for "mm/dd/yy".
I also tried DateTime.Parse(), Convert.ToDateTime() and got same error.
How can I filter this product list by create date?
"mm" is minutes, and your year is 4 digits, not 2. You want "MM/dd/yyyy", if your format is really always that. How confident are you on that front? (In particular, if it's entered by a user, you should probably make your code culture-sensitive...)
I would suggest pulling the parsing part out of the query though, and also probably using the invariant culture for parsing if you've really got a fixed format:
DateTime date = DateTime.ParseExact(EnteredDate, "MM/dd/yyyy",
CultureInfo.InvariantCulture);
var dates = Products.Where(d => d.CreateDate >= date);
Call
DateTime.ParseExact(EnteredDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);

How to get yesterday's date in C#

I want to retrieve yesterday's date in my ASP.NET web application using C#.
I've tried searching for a solution but have not had much success. The code I'm using just outputs today's date:
string yr = DateTime.Today.Year.ToString();
string mn = DateTime.Today.Month.ToString();
string dt = DateTime.Today.Day.ToString();
date = string.Format("{0}-{1}-{2}", yr, mn, dt);
How can I get yesterday's date?
Use DateTime.AddDays() method with value of -1
var yesterday = DateTime.Today.AddDays(-1);
That will give you : {6/28/2012 12:00:00 AM}
You can also use
DateTime.Now.AddDays(-1)
That will give you previous date with the current time e.g. {6/28/2012 10:30:32 AM}
The code you posted is wrong.
You shouldn't make multiple calls to DateTime.Today. If you happen to run that code just as the date changes you could get completely wrong results. For example if you ran it on December 31st 2011 you might get "2011-1-1".
Use a single call to DateTime.Today then use ToString with an appropriate format string to format the date as you desire.
string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
You don't need to call DateTime.Today multiple times, just use it single time and format the date object in your desire format.. like that
string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");
OR
string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
You will get yesterday date by this following code snippet.
DateTime dtYesterday = DateTime.Now.Date.AddDays(-1);
var yesterday = DateTime.Now.AddDays(-1);
Something like this should work
var yesterday = DateTime.Now.Date.AddDays(-1);
DateTime.Now gives you the current date and time.
If your looking to remove the the time element then adding .Date constrains it to the date only ie time is 00:00:00.
Finally .AddDays(-1) removes 1 day to give you yesterday.
string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");
DateTime dateTime = DateTime.Now ;
string today = dateTime.DayOfWeek.ToString();
string yesterday = dateTime.AddDays(-1).DayOfWeek.ToString(); //Fetch day i.e. Mon, Tues
string result = dateTime.AddDays(-1).ToString("yyyy-MM-dd");
The above snippet will work. It is also advisable to make single instance of DateTime.Now;
DateTime.Today as it implies is todays date and you need to get the Date a day before so you subtract one day using AddDays(-1);
There are sufficient options available in DateTime to get the formatting like ToShortDateString depending on your culture and you have no need to concatenate them individually.
Also you can have a desirable format in the .ToString() version of the DateTime instance

How to validate if a "date and time" string only has a time?

I have a single string variable that stores what could be a full date or a partial date:
1) Full Date: 12/12/2010 12:33 AM
2) Partial Date: 12:33 AM (no date field only time)
I'm trying to figure out what would be the best approach to parse the string to figure out if the string is missing the date string or not. The reason is, in my code if the date is missing I will append a default date to the string (such as 1/1/1900). Keep in mind that the time could be in various formats.
Update - My particular answer to this problem.
As all the "posts" have stated, there are multiple answers to this problem, this is ultimately what I used and hope it can help others*:
public DateTime ProcessDateAndTime(string dateString)
{
string dateAndTimeString = dateString;
string[] timeFormats = new string[]
{
"hh:mm tt", "hh:mm:ss tt",
"h:mm tt", "h:mm:ss tt",
"HH:mm:ss", "HH:mm", "H:mm"
};
// check to see if the date string has a time only
DateTime dateTimeTemp;
if (DateTime.TryParseExact(dateString, timeFormats,
CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out dateTimeTemp))
{
// setting date to 01/01/1900
dateAndTimeString = new DateTime(1900, 1, 1).ToShortDateString() + " " + dateString;
}
return DateTime.Parse(dateAndTimeString);
}
*Note: This method is based on the assumption that there are only a specific amount of time formats used in your application, and that it is guaranteed that a properly formatted date and time, or time only string passed in (pre-validation for removal of garbage text).
Use
Convert.ToDateTime(string value, IFormatProviderProvider provider)
Since the string comes in different flavors, provide different format providers as needed.
The order could be:
DateOnly
Time Only
DateTime
The convert will throw an format exception if it fails. If you prefer not to have exceptions, use Datetime.TryParse instead as that returns a boolean.
Depending on how the string is represented you could have more than 3 format providers.
You can try to validate string with a RegEx,
BTW, good regexes for DateTime validation can be found here
Here's one way to do this without knowing all possible time formats:
CultureInfo provider = CultureInfo.CurrentCulture;
DateTime time;
DateTime datetime;
bool isTime = DateTime.TryParse(dateString, provider, DateTimeStyles.NoCurrentDateDefault, out time)
&& time.Date == DateTime.MinValue.Date
&& DateTime.TryParse(dateString, provider, DateTimeStyles.None, out datetime)
&& datetime.Date != DateTime.MinValue.Date);
If the string only has a time then the first TryParse will set the date part to 1/1/0001 or DateTime.MinValue.Date and the second TryParse will set the date part to the current date. This will work unless it is run by Doctor Who after travelling back in time to 1/1/0001.
You can use DateTime.TryParseExact.
This might not be the best but it answers your question:
string dateString = "9:53AM";
if (!dateString.Contains('/')))
{
dateString = DateTime.Now.ToShortDateString() + " " + dateString;
}
Looking at the length of the string will be straight-forward and will support multiple formats. A string with a date and time will most certainly be longer than a string with just a time. However, if your input may have times with high precision (12:30:30:50:20 vs 12/11/11 12:30) and low precision this won't work.
This solution is ideal if you don't need to know the value in the string immediately, and only want to add the default date.
If you support times to the second, for instance, a time will have 8 or less characters and a date-time will have 9 or more.
Given that the time can be in various formats (12/24?) it would be best to user several patterns, in some pre-defined order, trying to parse with each and resolving when the first succeeds.
You can also try
DateTime aTime;
if (DateTime.TryParse(dateString, CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.NoCurrentDateDefault, out aTime))
{
//if the there is no date part in the dateString, date will
// default to Gregorian 1/1/0001
}

Categories

Resources