I'm trying to get my first ever C# application working as intended. :)
This application is a time converter, which allows user to input numbers into six different text boxes. For example, user puts 2009 into yyyy.Text, 20 into dd.Text, 02 into M.text, 02 into hh.Text, 49 into mm.Text and 35 into ss.Text. Then the program converts the numbers into a hexadecimal string.
For example,
2009 20 02 02:49:35 -> 63370694975000000 -> E1234FB3278DC0
private void button1_Click(object sender, EventArgs e)
{
String dateString = yyyy.Text + dd.Text + M.Text + hh.Text + mm.Text + ss.Text;
DateTime timestamp = DateTime.ParseExact(dateString, "yyyy dd M hh:mm:ss", CultureInfo.CurrentCulture);
long ticks = timestamp.Ticks;
long microseconds = ticks / 10;
convertedText.Text = microseconds.ToString("X");
}
The application is compiled fine, but after putting numbers into the text boxes and clicking the 'Convert' button, the program crashes. The error: Additional information: String was not recognized as a valid DateTime.
Am I using the wrong DataTime format? or something? :(
Thanks in advance... I wanna get this working :)
I think you need spaces and colons as you declare in the format.
When making the dateString, don't forget to insert spaces.
Use
String.Format("{0} {1} {2} {3}:{4}:{5}",yyyy.Text, dd.Text, M.Text, hh.Text, mm.Text, ss.Text)
And, place a try-catch block - it's the easiest way to catch exceptions when converting, (although not recommended for a good program), in case the user inputs some insane numbers and text.
Your dateString does not correspond to the format you specified - you have a string without any separators (like spaces or colons). Format the string accordingly to your format. Also, it is always a good idea to use format utils. But I think you should use string, not String:
string dateString = string.Format("{0} {1} {2} {3}:{4}:{5}",
yyyy.Text, dd.Text, M.Text, hh.Text, mm.Text, ss.Text);
Try to insert a breakpoint on the DateTime timestamp = DateTime.ParseExact(dateString, "yyyy dd M hh:mm:ss", CultureInfo.CurrentCulture) line.
Then before you execute that command, hover your mouse over dateString. Then I think you will see that dateString does nto match the format you have provided to ParseExact at all.
When the string matches the format you have given, it should work fine.
Good luck! :)
Try this
Solution 1:
private void button1_Click(object sender, EventArgs e)
{
DateTime timestamp = new DateTime(
Convert.ToInt32(yyyy.Text)
, Convert.ToInt32(M.Text)
, Convert.ToInt32(dd.Text)
, Convert.ToInt32(hh.Text)
, Convert.ToInt32(mm.Text)
, Convert.ToInt32(ss.Text));
long ticks = timestamp.Ticks;
long microseconds = ticks / 10;
convertedText.Text = microseconds.ToString("X");
}
Solution 2:
private void button1_Click(object sender, EventArgs e)
{
string dateString = string.Format("{0}/{1}/{2} {3}:{4}:{5}", M.Text,dd.Text,yyyy.Text, hh.Text, mm.Text, ss.Text);
long ticks = Convert.ToDateTime(dateString).Ticks;
long microseconds = ticks / 10;
convertedText.Text = microseconds.ToString("X");
}
Output:
E1234FB3278DC0
Related
I am creating my first win form application, written in C#. I have added a little bit of code to display the current date and time on the first tab page as below:
private void Form1_Load(object sender, EventArgs e)
{
// connect to database
c = new Connection();
connect.ConnectionString = c.getConnection();
//deals with date and time
Timer tmr = new Timer();
tmr.Interval = 1000;//ticks every 1 second
tmr.Tick += new EventHandler(tmr_Tick);
tmr.Start();
}
private void tmr_Tick(object sender, EventArgs e)
{
labeltime.Text = DateTime.Now.ToString(" Todays Date: dd/MM/yyyy\n\n Current Time: HH:mm:ss");
}
The output in not correct however. The date and time are correct and ticking away nicely but where I want it to display "Todays Date:" it is messy like " To15a1342 (42 being the seconds from the time, ticking away) and the "Current Time" reads CuRRenP Ti50e:
Does it matter that I am in the UK? Would this require me to use different code or something?
Your text is being interpreted as formatting strings, as explained in DateTime.ToString(string format):
The format parameter should contain either [...] a custom format pattern (see Custom Date and Time Format Strings)
Only unrecognized characters are printed as-is, but as you noticed for example the s gets replaced by the value of Seconds.
To let ToString() ignore your text, you need to escape the literals, preferably with single quotes (') (the alternative is a backslash in front of each literal):
string dateTimeString = DateTime.Now
.ToString("' Todays Date: 'dd/MM/yyyy'\n\n Current Time: 'HH:mm:ss");
Or build up the string from separate parts:
var now = DateTime.Now;
string dateTimeString = "' Todays Date: ";
dateTimeString += now.ToString("dd/MM/yyyy");
dateTimeString += "\n\n Current Time: ";
dateTimeString += now.ToString("HH:mm:ss");
Above string concatenation example can in turn be simplified as #Rohit's answer demonstrates.
Use String.Format like this:
string dateTime = String.Format("Todays Date: {0}, Current Time: {1}",
DateTime.Now.ToString("dd/mm/yyyy"),
DateTime.Now.ToString("hh:mm:ss"));
I'm trying to compile my first C# application (based on Visual Studio) ... also using Windows Forms for input (from user) and output.
User puts numbers into six text boxes (e.g. 2009 20 02 02:49:35) and then when the 'Convert' button is clicked, the program outputs E1234FB3278DC0 in a different text box.
Not sure if this is relevant but E1234FB3278DC0 = 63370694975000000 (in decimal).
oh also, I'm not sure about convertedText.writeline... should it be this.textBox7 = microseconds; ?
String dateString = yyyy.Text + dd.Text + mm.Text + hh.Text + mm.Text + ss.Text;
DateTime timestamp = DateTime.ParseExact(dateString, "yyyy dd mm hh:mm:ss", CultureInfo.CurrentCulture);
long ticks = timestamp.Ticks;
long microseconds = ticks / 10;
convertedText.WriteLine(microseconds.ToString("X"));
Thanks in advance..
And I gotta thank Luxspes for the orginal version.
Some tips about this code snippet.
String dateString = yyyy.Text + dd.Text + mm.Text + hh.Text + mm.Text + ss.Text;
DateTime timestamp = DateTime.ParseExact(dateString, "yyyy dd mm hh:mm:ss", CultureInfo.CurrentCulture);
First of all, it's really strange that you use the same "mm"-object for months and minutes. The same problem with format specifier. To parse month you should use 'M'.
long ticks = timestamp.Ticks;
long microseconds = ticks / 10;
convertedText.WriteLine(microseconds.ToString("X"));
So, if your date parsed successfully you'll get the number of microseconds that have elapsed since 12:00:00 midnight, January 1, 0001. It's E1234FB3278DC0 in hexadecimal (for the date in your question).
But in your case date represented in the seconds. So, the number of microseconds will be always.
timestamp.Millisecond*1000;
I have no idea about the type of convertedText object. But it seems to me that's not a problem.
Try to use the following code:
String dateString = yyyy.Text+dd.Text+M.Text+hh.Text+mm.Text+ss.Text;
DateTime dateTime = DateTime.ParseExact(dateString, "yyyy dd M hh:mm:ss", CultureInfo.CurrentCulture);
long microseconds = dateTime.Ticks/10;
convertedText.Text = microseconds.ToString("X");
How to get the selected date of a MonthCalendar control in C# (Window forms)
"Just set the MaxSelectionCount to 1 so that users cannot select more than one day. Then in the SelectionRange.Start.ToString(). There is nothing available to show the selection of only one day." - Justin Etheredge
From here.
I just noticed that if you do:
monthCalendar1.SelectionRange.Start.ToShortDateString()
you will get only the date (e.g. 1/25/2014) from a MonthCalendar control.
It's opposite to:
monthCalendar1.SelectionRange.Start.ToString()
//The OUTPUT will be (e.g. 1/25/2014 12:00:00 AM)
Because these MonthCalendar properties are of type DateTime. See the msdn and the methods available to convert to a String representation. Also this may help to convert from a String to a DateTime object where applicable.
Using SelectionRange you will get the Start and End date.
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
var startDate = monthCalendar1.SelectionRange.Start.ToString("dd MMM yyyy");
var endDate = monthCalendar1.SelectionRange.End.ToString("dd MMM yyyy");
}
If you want to update the maximum number of days that can be selected, then set MaxSelectionCount property. The default is 7.
// Only allow 21 days to be selected at the same time.
monthCalendar1.MaxSelectionCount = 21;
For those who are still trying, this link helped me out, too; it just puts it all together:
http://dotnetslackers.com/VB_NET/re-36138_How_To_Get_Selected_Date_from_MonthCalendar_control.aspx
private void MonthCalendar1_DateChanged(object sender, System.Windows.Forms.DateRangeEventArgs e)
{
//Display the dates for selected range
Label1.Text = "Dates Selected from :" + (MonthCalendar1.SelectionRange.Start() + " to " + MonthCalendar1.SelectionRange.End);
//To display single selected of date
//MonthCalendar1.MaxSelectionCount = 1;
//To display single selected of date use MonthCalendar1.SelectionRange.Start/ MonthCalendarSelectionRange.End
Label2.Text = "Date Selected :" + MonthCalendar1.SelectionRange.Start;
}
It'll be helpful if you want just to convert it by:
String myCalendar = monthCalendar1.SelectionRange.Start.ToShortDateString()
But if you want to get a formatted output you could instead:
String myCalendar = monthCalendar1.SelectionRange.Start.ToString("yyyy-MM-dd")
It's important to use year and day as lower caps, and month as upper or else it'll return you a wrong format, for example, if you do:
String myCalendar = monthCalendar1.SelectionRange.Start.ToString("YYYY-MM-DD")
it will return: YYYY-07-DD (If the original date's month was July)
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
string clickeddate = monthCalendar1.SelectionRange.Start.ToString("dddd, dd MMM yyyy");
richTextBox.AppendText(clickeddate); //or whatever you decide to do with it.
}
SelectionRange property
Time.ToString("0.0") shows up as a decimal "1.5" for instead of 1:30. How can I get it to display in a time format?
private void xTripSeventyMilesRadioButton_CheckedChanged(object sender, EventArgs e)
{
//calculation for the estimated time label
Time = Miles / SeventyMph;
this.xTripEstimateLabel.Visible = true;
this.xTripEstimateLabel.Text = "Driving at this speed the estimated travel time in hours is: " + Time.ToString("0.0") + " hrs";
}
Time.ToString("hh:mm")
Formats:
HH:mm = 01:22
hh:mm tt = 01:22 AM
H:mm = 1:22
h:mm tt = 1:22 AM
HH:mm:ss = 01:22:45
EDIT: Since now we know the time is a double change the code to (assuming you want hours and minutes):
// This will handle over 24 hours
TimeSpan ts= System.TimeSpan.FromHours(Time);
string.Format("{0}:{1}", System.Math.Truncate(ts.TotalHours).ToString(), ts.Minutes.ToString());
or
// Keep in mind this could be bad if you go over 24 hours
DateTime.MinValue.AddHours(Time).ToString("H:mm");
If Time is a System.Double, then System.TimeSpan.FromHours(Time).ToString();
I guess that Time is of type TimeSpan? In that case, the documentation of TimeSpan.ToString can help you, in particular the pages
Standard TimeSpan Format Strings and
Custom TimeSpan Format Strings.
If Time is a numeric data type, you can use TimeSpan.FromHours to convert it to a TimeSpan first.
(EDIT: TimeSpan format strings were introduced in .NET 4.)
Note that if you work in a 24-hour base, it's very important to use HH:mm and NOT hh:mm.
Sometimes I mistakenly write hh:mm, and then instead of "13:45" I get "01:45", and there's no way to know whether it's AM or PM (unless you use tt).
If time is float or double you'll have to.
System.Math.Truncate(Time) to get the hours
and then (Time - System.Math.Truncate(Time))* 60
to get the minutes.
Thanks for all of the responses guys and gals i used this DateTime.MinValue.AddHours(Time).ToString("H:mm");for my program since it was the easiest one to implement.
Create a timespan from you numeric variable:
TimeSpan ts = new TimeSpan(Math.Floor(Time), (Time - Math.Floor(Time))*60);
Then, use the ToString method.
in c# i have time in format hhmmss like 124510 for 12:45:10 and i need to know the the TotalSeconds. i used the TimeSpan.Parse("12:45:10").ToTalSeconds but it does'nt take the format hhmmss. Any nice way to convert this?
This might help
using System;
using System.Globalization;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
DateTime d = DateTime.ParseExact("124510", "hhmmss", CultureInfo.InvariantCulture);
Console.WriteLine("Total Seconds: " + d.TimeOfDay.TotalSeconds);
Console.ReadLine();
}
}
}
Note this will not handle 24HR times, to parse times in 24HR format you should use the pattern HHmmss.
Parse the string to a DateTime value, then subtract it's Date value to get the time as a TimeSpan:
DateTime t = DateTime.ParseExact("124510", "HHmmss", CultureInfo.InvariantCulture);
TimeSpan time = t - t.Date;
You have to decide the receiving time format and convert it to any consistent format.
Then, you can use following code:
Format: hh:mm:ss (12 Hours Format)
DateTime dt = DateTime.ParseExact("10:45:10", "hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
double totalSeconds = dt.TimeOfDay.TotalSeconds; // Output: 38170.0
Format: HH:mm:ss (24 Hours Format)
DateTime dt = DateTime.ParseExact("22:45:10", "HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
double totalSeconds = dt.TimeOfDay.TotalSeconds; // Output: 81910.0
In case of format mismatch, FormatException will be thrown with message: "String was not recognized as a valid DateTime."
You need to escape the colons (or other separators), for what reason it can't handle them, I don't know. See Custom TimeSpan Format Strings on MSDN, and the accepted answer, from Jon, to Why does TimeSpan.ParseExact not work.
In case you want to work with also milliseconds like this format "01:02:10.055" then you may do as following;
public static double ParseTheTime(string givenTime)
{
var time = DateTime.ParseExact(givenTime, "hh:mm:ss.fff", CultureInfo.InvariantCulture);
return time.TimeOfDay.TotalSeconds;
}
This code will give you corresponding seconds.
Note that you may increase the number of 'f's if you want to adjust precision points.
If you can guarantee that the string will always be hhmmss, you could do something like:
TimeSpan.Parse(
timeString.SubString(0, 2) + ":" +
timeString.Substring(2, 2) + ":" +
timeString.Substring(4, 2)))