Got the time of day? - c#

I'm stuck in a hole, and I cannot for the life of me dig myself out of it.
This is a highly aesthetics question, but I like to get what I ask for from my code.
I'm trying to parse a string representing time to a DateTime variable that I then send to a textBox as well as to my LINQ query.
I would like to represent my time in this format: "yyyy-MM-dd hh:mm:ss" and that is what i get from my Select query, but as soon a I try to parse what the user has written in the textBox to DateTime it gives me "1/13/2011 12:00:00 AM", even if it was in the format "2011-01-13 00:00:00".
I feel like I've tried everything to make this work, but there must be a solution, can you guys help me find it? What IFormatProvider am I suppose to use?
This is what i tried:
//textBox1.Text = "2011-01-13 00:00:00";
DateTime = TimeFrom;
TimeFrom = DateTime.ParseExact(textBox1.Text, "yyyy-MM-dd hh:mm:ss", null);
TimeFrom = DateTime.ParseExact(textBox1.Text, CultureInfo.CurrentCulture.DateTimeFormat.GetAllDateTimePatterns(), new CultureInfo("sv-SE"), DateTimeStyles.None);
TimeFrom = DateTime.ParseExact(textBox1.Text, CultureInfo.CurrentCulture.DateTimeFormat.GetAllDateTimePatterns(), new CultureInfo("sv-SE"),System.Globalization.DateTimeStyles.AssumeUniversal);
TimeFrom = DateTime.ParseExact("2008-10-01 16:44:12.000", "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.CreateSpecificCulture("en-US"));
textBox1.Text = TimeFrom.ToString();
But none of it gives me the formatting that I so crave.
UPDATE:
It appears that somehow the Current Culture got changed from the time I declared my DateTime variable to the time I wanted to Parse the textBox1.Text value from "sv-SE" to "en-EN" which is why it decided to change the way my time was formatted. It is not something I'm doing in my code. Any ideas as to why?
Why it decided to ignore my (IFormatProvider) new CultureInfo("sv-SE",true), is something I haven't figured out yet ether.
If you have any suggestions, please let me know.

textBox1.Text = TimeFrom.ToString("yyyy-MM-dd hh:mm:ss");
or something like:
textBox1.Text = TimeFrom.ToString(new CultureInfo("sv-SE"));
depending on what you need exactly.

Parsing means to take a string and turn it into a strongly-typed DateTime object, using a format.
To turn that strongly-typed DateTime object into a string, you call ToString using a format.
TimeFrom.ToString("yyyy-MM-dd hh:mm:ss");
Edit: Maybe you just need to set the Thread.CurrentThread.CurrentCulture = new CultureInfo("sv-SE") before you start doing stuff. Is this an ASP.NET app?

Have you tried
TimeFrom.ToString("yyyy-MM-dd hh:mm:ss");
You need to format DateTime only when you convert it to String.

Have you tried InvariantCulture? To print out the string in a certain format take a look at format strings

Hey guys. I just wanted to go public with what caused my problems.
What happened was that when I rendered a report and loaded it into a report viewer the CurrentCulture got changed to en-EN. The report language was set to blank which leads me to believe that the default language is en-EN.
This then changed the way that my time was represented. A DateTime variable does not remember its formatting culture. So any changes in representing a DateTime as a string has to contain the string formatting, like this: dateTimeVariable.toString("yyyy-MM-dd hh:mm:ss")
I hope someone will find this helpfull.

Related

Parse Time String to DateTime format for HH:MM format of DateTimePicker - C#, WFA

I am trying to take a time string in the format of HH:MM such as 18:30 and turning this into a DateTime string.
I have tried many different methods such as using ParseExact (as seen below), however even when using this code, it still outputs the DateTime string as both the date and the time.
dtpTime.Value = DateTime.ParseExact(Classes.SystemClasses.Booking.getBookingTime(), "H:mm", null, System.Globalization.DateTimeStyles.None);
Which outputs:
20/02/2019 18:56:00
The value in Classes.SystemClasses.Booking.getBookingTime() is 18:56 which is the value I wish to enter into a DateTimePicker on a form in the format of HH:MM
Any help to resolve this problem would be greatly appreciated and if the explanation is not clear enough, please feel free to ask myself any questions.
Thanks, Ryan.
What you are trying to do is hold a TIME inside a DateTime variable. That is not possible, as the name suggest, this type is used to hold a Date and a Time. If you need only the Time part of the date, you need to convert it to a string:
var time = DateTime.ParseExact(Classes.SystemClasses.Booking.getBookingTime(), "HH:mm", null, System.Globalization.DateTimeStyles.None).ToString("HH:mm");

date month not displaying correctly

why is
string date = string.Format("{0:mmddyyHHmmss}",
DateTime.Now);
giving me 420813104204
shouldn't it be 040813... ?
I am trying to match
mmddyyHHmmSS
You need to use MM for month not mm, mm is for minutes not months.
string date = string.Format("{0:MMddyyHHmmss}",
You can find more about formats here.
try this instead
string date = string.Format("{0:MMddyyHHmmss}", DateTime.Now);
string date = string.Format("{0:MMddyyHHmmss}", DateTime.Now);
would give you the required format.
Check out this link for reference
That's because mm is for the minute not months, you need to use MM. You can see the definition for custom date time strings here.
string date = string.Format("{0:MMddyyHHmmss}",
Further, I generally don't use string.Format with DateTime objects because I've seen some anomalies when it comes to parsing them across different cultures. Leveraging the ToString method on the DateTime object for me has always been more reliable. That's just something I've seen - it also could be that I was doing something wrong with the string.Format. I wish I could build an example of that right now but I don't even remember what those anomalies are now - I just remember having problems so I switched.

String was not recognized as a valid DateTime

I know such questions are in ton in SO but my situation seems little weird to me.
I have a textbox with a calendar extender control on my aspx page
Default format is "d" in extenders date format property.
When I choose my date say 15th May 2012 from the calendar,it gives me 5/15/2012, which is fine.
Since its a string and my db field is oftype datetime, so I am using
Convert.ToDateTime(TextBox.Text); // TextBox.Text = 5/15/2012
But it throws the exception,
string was not recognized as valid datetime.
I then Change the code and used DateTime.Parse() but the issue remains. Then i tried to reformat the date something like this,
Convert.ToDateTime(string.Format("0:MM-dd-yyyy",TextBox.Text)).Date
but still its throwing exceptions..
Please help me.
Use the following,
DateTime dt = DateTime.ParseExact(TextBox.Text, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
There's probably a difference between your system's DateTime format and the DateTiem format the extender uses.
I suppose that your dev machine date-time format is not equal to MM/DD/YYYY, but something else (for example DD/MM/YYYY). Have a look on your computer Regional settings to see your system date time format.

MVC C# DateTime formatting fix needed

As you can see in the below screen shot. I have Date which is 7/12/2011 12:00:00 AM. Date is described wrong even if I format it. 7 should be the day and 12 is the month.
How I fix that to get proper formatting for yellow return string?
In the below screen shot the Date is 28/12/2011 11:00 where 28 is day and 12 is month. Trying to convert that string into DateTime to save into SQL Server DateTime field but gives conversion problem. Anyone tell me why is that and How to fix it?
Solution:
I solved problem like below. When I want saving date in SQL Server 2008 r2 the default was saved like 2011-08-12 11:00:00.000 which was causing problem. I changed that formatting Date when it was going to be saved in SQL like below and it worked
DateTime n = Convert.ToDateTime(start_date);
var h = String.Format("{0:dd/MM/yyyy}", n);
if (start_date != "")
{
changedEvent.start_date = Convert.ToDateTime(h);
}
Output now is 2011-12-08 11:00:00.000. Do you think any clean work around?
You should call DateTime.ParseExact(start_date, "dd/MM/yyyy", CultureInfo.InvariantCulture)
Try:
DateTime.ParseExact(str, "dd/MM/yyyy HH:mm:ss TT", null); //28/12/2011 11:00:00 AM
DateTime.ParseExact(str, "dd/MM/yyyy HH:mm", null); //28/12/2011 11:00
I think you are addressing the wrong problem. If you want DateTime to recognize your locale date format, then you should make sure the servers date locale is set for your local one. Then, DateTime will convert the date correctly without conversion.
If that's not possible (say you're using a shared server in a different locale) then the ParseExact method would be one solution, but it will only fix some of the problem. For instance, dates posted and model bound will attempt to parse in the servers locale format.
You may need to set your locale explicitly, using something like this:
Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-MX");

date from string help. I can convert to the string I want, but I can't convert back

I have a string I need to convert back to a date. I can call .ToString("yyyyMMdd") and get the string i want. My question is how can I convert that back into a date? I'm trying something like the following with no luck.
DateTime d;
var formatInfo = new DateTimeFormatInfo {ShortDatePattern = "yyyyMMdd"};
if (DateTime.TryParse(details.DetectionTime.Date, formatInfo, DateTimeStyles.None, out d))
{
lit.Text = d.ToShortTimeString(); //would like 07/30/2010 as the text
}
I've never used DateTimeFormatInfo before if that isn't obvious. Can someone point me in the right direction. I know I could probably use substring and create a new DateTime(y, m, d) etc... I'm just wondering since c# interpreted .ToString() correctly, if it can't derive a date from the very same string it output.
The reverse of DateTime.ToString("yyyyMMdd") is DateTime.TryParseExact, passing "yyyyMMdd" as a format string.
IFormatProvider is a bit of a red herring. You'll normally pass either :
Thread.CurrentThread.Culture, if you're parsing a date typed by the user, when you should obey the user's date preferences
Or CultureInfo.InvariantCulture, if you're parsing a date provided by a program, when your behaviour shouldn't depend on the preferences the user has set up
Use d.ToString("MM/dd/yyyy")
For more options check out http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx
Edit: Read it wrong
Use DateTime.Parse() to parse the string to a datetime.
http://msdn.microsoft.com/en-us/library/1k1skd40.aspx
You can also use DateTime.TryParse to see if the string is able to convert to a date first.
http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx
Alternatively you can also use Convert.ToDateTime()
If you want the DateTime variable back after sending it to a string, save yourself the trouble and just cache or pass the actual DateTime variable around scopes to wherever you need it later and don't bother converting the text back into a DateTime class..
Sorry I just realized this doesn't answer your request, so what you're looking for is:
DateTime.ParseExact(someDateTime, "the format string you used to .tostring generating the string", null);
Convert.ToDateTime("07/30/2010");
I'm assuming you mean to convert a string to a DateTime format. If so use this:
DateTime yourStringConverted = Convert.ToDateTime( yourString );

Categories