Omitting date from label text, only showing time - c#

The following code displays the label as Planning horizon: 20/11/2014 08:00:00 to 20/11/2014 09:00:00, how do I get it to display it as Planning horizon: 08:00:00 to 09:00:00.
DateTime startTime = DateTime.Parse("08:00:00");
DateTime endTime = DateTime.Parse("09:00:00");
label1.Text = "Planning horizon: " + startTime + " to " + endTime;

Use .ToLongTimeString() or .ToShortTimeString() on your DateTimes.
DateTime x = DateTime.Now;
Console.WriteLine(x.ToLongTimeString());
Console.WriteLine(x.ToShortTimeString());
Will Generate:
9:30:20 AM
9:30 AM
For your specific output you may want to customize the output string, so instead do this:
startTime.ToString("HH:mm:ss")
Which outputs (note the HH outputs in a 24 hour clock):
09:30:14
See this MSDN page for more info on formatting time strings.

Just format your DateTime's with .ToString() method like;
label1.Text = "Planning horizon: " + startTime.ToString("HH:mm:ss") + " to "
+ endTime.ToString("HH:mm:ss");
Long Answer
Since you using string + DateTime concatenation, this process will call string + object overload and uses .ToString() method for the second parameter.
From DateTime.ToString() method;
The value of the current DateTime object is formatted using the
general date and time format specifier ('G').
This method uses formatting information derived from the current
culture. In particular, it combines the custom format strings returned
by the ShortDatePattern and LongTimePattern properties of the
DateTimeFormatInfo object returned by the
CurrentCulture.DateTimeFormat property
And looks like your CurrentCulture's ShortDatePattern and LongTimePattern is dd/MM/yyyy and HH:mm:ss. That's why you get string result based these concated formats.

Use the TimeOfDay function. See the link below for formatting options.
http://msdn.microsoft.com/en-us/library/system.datetime.timeofday%28v=vs.110%29.aspx

Related

How to remove time in second after retrieve from database?

i have this label retrieve time from database and display in label. but time in database also consist of second for example 03:45:29, how can i remove the time in second to become 03:45 in the label after retrieve it. this is my code:LabelDateMarker.Text = LabelDateMarker.Text + " " + dr[3].ToString();
Assuming dr is a SqlDataReader or similar, you probably want to cast to DateTime, then format the value appropriately:
DateTime dateTime = (DateTime) dr[3];
string formatted = dateTime.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
LabelDateMarker.Text += " " + formatted;
Here yyyy-MM-dd HH:mm is a custom date/time format string indicating that you want the hours and minutes after the ISO-8601-formatted date part.
I've used the invariant culture when formatting to avoid this giving unexpected results in locales that don't use the Gregorian calendar by default.
(I've assumed the value is always non-null. If it might be null, you should check it with dr.IsDBNull(3) first.)
Use a format string for this
((DateTime)dr[3]).ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
instead of
dr[3].ToString();
For more information have a look at the available formats at the MSDN

DateTime parsing error while parsing dd/MM/yyyy format. String was not recognized as valid datetime

I create a string using values from certain page elements in my web user control as below
string bookingdate = ddlDate.SelectedItem.Text
+ "/" + ddlMonth.SelectedValue + "/"
+ ddlMonth.SelectedItem.Text.Substring(4, 2);
and getting "String was not recognized as a valid DateTime." error on the following line
cmd.Parameters.Add(new SqlParameter("#ArrivalDate", SqlDbType.DateTime)).Value =
DateTime.ParseExact(bookingdate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
How can I alter the value of this string "bookingdate" to troubleshoot the problem.
So ddlMonth contains items in this format (you posted the link to your page):
<option value="08">Aug 14</option>
Now you're trying to extract the month and year part from it:
ddlMonth.SelectedValue + "/" + ddlMonth.SelectedItem.Text.Substring(4, 2)
Your format string is this: dd/MM/yyyy
Do you already see the problem? The format string expects four digits for the year.
Instead use this format string: dd/MM/yy
DateTime.ParseExact(bookingdate, "dd/MM/yy", CultureInfo.InvariantCulture);
As I can understand you need Indian Date Format that is dd/mm/yyyy. So in your code, pass parameter as string and in sql handle it using Convert(date,Convert(datetime,#ArrivalDate,103)). Use date as your datatype if you need only date and is on Sql 2008 or above otherwise
Convert(datetime,#ArrivalDate,103) and leave your datatype as datetime
In cs:
cmd.Parameters.AddWithValue("#ArrivalDate", bookingdate);

DateTime.Parse throwing format exception

I retrieve date and time strings from xml by parsing XElement.
The date and time values are retrieved by
file.Element("Date").Value and file.Element("Time").Value respectively.
After I retrieve the Date value I parse it to a DateTime variable
DateTime dt,ts;
dt = file.Element("Date").Value; // the value is say 12/29/2012
and then this dt value is set to a datepicker value on the xaml UI
datepicker.Value = dt;
I also have a timepicker whose value have to be set by the Time value retrieved from xml.
To set the timepicker value I do the following.
declare 3 strings, say:
string a = file.Element("Time").Value; // the value is say 9:55 AM
string b = file.Element("Time").Value.Substring(0, 5) + ":00"; // eg 9:55:00
string c = file.Element("Time").Value.Substring(5); // the value is ' AM'
I then concatenate the Date Value and string 'b' and 'c'
string total = file.Element("Date").Value + " " + b + c;
the value of total is now '12/29/2012 9:55:00 AM'
I then try to Parse this total string to a DateTime, but it throws a formatexception
DateTime.Parse(total, CultureInfo.InvariantCulture);
Any help appreciated...
Try DateTime.ParseExact
var dateStr = "12/29/2012 09:55:00 AM";
DateTime date = DateTime.ParseExact(dateStr,"MM/dd/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
Demo here.
Read C# DateTime Format for format string detail.
Note that i have added extra 0 to hour part. It must be 2 digits otherwise format exception will occur.
Try using: DateTime.ParseExact
string total = '12/29/2012 9:55:00 AM';
string format = "MM/dd/yyyy H:mm:ss tt";
DateTime dateTime = DateTime.ParseExact(dateString, format,
CultureInfo.InvariantCulture);
I have got the solution for this.
When trying to save the datepicker in XML format, I was saving the value of timepicker as XMLElement as ValueString, hence when converted to string always throwed error.
So I saved it in XML format as Value.ToString().
Now it can convert correctly from String to Date or Time equivalents.

C# Parsing Dates and Times

I have some code in app along the lines of
DateTime activityDate = DateTime.Parse(tempDate + " " + tempTime);
Where tempDate is a string with values such as "2009-12-01" ( i.e. yyyy-mm-dd )
and tempTime is a string with values such as "23:12:10" ( i.e. hh:mm:ss )
Firstly, is there a better way to combine these to get a DateTime, and secondly is the code above safe to work in any region ( if not is there a way to handle this )
Hmm looking at the date more closely the concatenated date & time is actually in this format "2009-11-26T19:37:56+00:00" - what's the format string for the timezone part of the date/time?
If the format is guaranteed, ParseExact may be safer (sepcifying the pattern):
DateTime activityDate = DateTime.ParseExact(tempDate + " " + tempTime,
"yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
You can use ParseExact to specify the date and time format.
e.g.:
DateTime dateTime =
DateTime.ParseExact("2009-12-01 23:12:10", "yyyy-MM-dd HH:mm:ss", null);
Which yields:
Assert.That(dateTime, Is.EqualTo(new DateTime(2009, 12, 1, 23, 12, 10)));
You can also specify the culture that uses this format and parse using it the date and time while keeping the parsing safe from the processing OS culture.
From a quick look it seems that there is no culture with this exact predefined format, but in general many standard formats exists in the framework cultures.
Use ParseExact. It's been asked a few times on SO.. Link1, Link2
You can use ParseExact to specify a format for the parsing. That way there is no risk for it to be parsed in any other way:
DateTime activityDate = DateTime.ParseExact(tempDate + " " + tempTime, "yyyy'-'MM'-'dd HH':'mm':'ss", CultureInfo.InvariantCulture);
As if you cared, another option would be to do:
DateTime activityDateOnly =
DateTime.ParseExact(tempDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
TimeSpan activityTime =
TimeSpan.ParseExact(tempTime, "hh':'mm':'ss", CultureInfo.InvariantCulture);
DateTime activityDate = activityDateOnly + activityTime;
Just an option...

String was not recognized as a valid DateTime " format dd/MM/yyyy"

I am trying to convert my string formatted value to date type with format dd/MM/yyyy.
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
What is the problem ?
It has a second override which asks for IFormatProvider. What is this? Do I need to pass this also? If Yes how to use it for this case?
Edit
What are the differences between Parse and ParseExact?
Edit 2
Both answers of Slaks and Sam are working for me, currently user is giving the input but this will be assured by me that they are valid by using maskTextbox.
Which answer is better considering all aspects like type saftey, performance or something you feel like
Use DateTime.ParseExact.
this.Text="22/11/2009";
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);
You need to call ParseExact, which parses a date that exactly matches a format that you supply.
For example:
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
The IFormatProvider parameter specifies the culture to use to parse the date.
Unless your string comes from the user, you should pass CultureInfo.InvariantCulture.
If the string does come from the user, you should pass CultureInfo.CurrentCulture, which will use the settings that the user specified in Regional Options in Control Panel.
Parsing a string representation of a DateTime is a tricky thing because different cultures have different date formats. .Net is aware of these date formats and pulls them from your current culture (System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat) when you call DateTime.Parse(this.Text);
For example, the string "22/11/2009" does not match the ShortDatePattern for the United States (en-US) but it does match for France (fr-FR).
Now, you can either call DateTime.ParseExact and pass in the exact format string that you're expecting, or you can pass in an appropriate culture to DateTime.Parse to parse the date.
For example, this will parse your date correctly:
DateTime.Parse( "22/11/2009", CultureInfo.CreateSpecificCulture("fr-FR") );
Of course, you shouldn't just randomly pick France, but something appropriate to your needs.
What you need to figure out is what System.Threading.Thread.CurrentThread.CurrentCulture is set to, and if/why it differs from what you expect.
Although the above solutions are effective, you can also modify the webconfig file with the following...
<configuration>
<system.web>
<globalization culture="en-GB"/>
</system.web>
</configuration>
Ref : Datetime format different on local machine compared to production machine
You might need to specify the culture for that specific date format as in:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); //dd/MM/yyyy
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
For more details go here:
http://msdn.microsoft.com/en-us/library/5hh873ya.aspx
Based on this reference, the next approach worked for me:
// e.g. format = "dd/MM/yyyy", dateString = "10/07/2017"
var formatInfo = new DateTimeFormatInfo()
{
ShortDatePattern = format
};
date = Convert.ToDateTime(dateString, formatInfo);
After spending lot of time I have solved the problem
string strDate = PreocessDate(data);
string[] dateString = strDate.Split('/');
DateTime enter_date = Convert.ToDateTime(dateString[1]+"/"+dateString[0]+"/"+dateString[2]);
private DateTime ConvertToDateTime(string strDateTime)
{
DateTime dtFinaldate; string sDateTime;
try { dtFinaldate = Convert.ToDateTime(strDateTime); }
catch (Exception e)
{
string[] sDate = strDateTime.Split('/');
sDateTime = sDate[1] + '/' + sDate[0] + '/' + sDate[2];
dtFinaldate = Convert.ToDateTime(sDateTime);
}
return dtFinaldate;
}
use this to convert string to datetime:
Datetime DT = DateTime.ParseExact(STRDATE,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat)
Just like someone above said you can send it as a string parameter but it must have this format: '20130121' for example and you can convert it to that format taking it directly from the control. So you'll get it for example from a textbox like:
date = datetextbox.text; // date is going to be something like: "2013-01-21 12:00:00am"
to convert it to: '20130121' you use:
date = date.Substring(6, 4) + date.Substring(3, 2) + date.Substring(0, 2);
so that SQL can convert it and put it into your database.
Worked for me below code:
DateTime date = DateTime.Parse(this.Text, CultureInfo.CreateSpecificCulture("fr-FR"));
Namespace
using System.Globalization;
You can use also
this.Text = "22112009";
DateTime newDateTime = new DateTime(Convert.ToInt32(this.Text.Substring(4, 4)), // Year
Convert.ToInt32(this.Text.Substring(2,2)), // Month
Convert.ToInt32(this.Text.Substring(0,2)));// Day
Also I noticed sometimes if your string has empty space in front or end or any other junk char attached in DateTime value then also we get this error message

Categories

Resources