Date & time not displaying correctly - c#

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"));

Related

How to display time in hours, mins, seconds, 100ths in datatable / datagridview

I am an embedded c programmer. I have used c# before but this is my first attempt at a complex, object oriented project.
I have created a datatable and linked to a datagridview for the purpose of displaying data in a windows form.
It's working well so far. The data is stored in int form and consists primarily of times since event information in 100ths of a second. (It's the front end for a race timing system). So for example 12345 means 123.45 seconds.
I would like to show this in the form 2:03.45
I know there is the option to store data in the datatable in date and time format. However I am not sure if this will do what I need...there is no date required and it doesn't seem to cover 100th of a second.
I could format a string perhaps but this seems a bit clunky so wanted to check there wasn't a better way. Also I need to be able to use the sort functionality of the datagridview to sort each column based on the shortest time. This currently works but I'm not sure it would do with strings?
You can create TimeSpan and then format it to whatever format you want:
TimeSpan span = TimeSpan.FromMinutes(123.45);
string label = span.ToString(#"hh\:mm\:ss\:ff");
Output:
02:03:27
So now if you want the output to be 123 to be in minutes and 45 to be seconds than
double smd = 123.45;
TimeSpan span = TimeSpan.FromMinutes(smd);
string label = span.ToString(#"hh\:mm") + ":" + (int) (((decimal) smd % 1) * 100);
Because you cannot use standard formats you need write your formatting logic to the DataGridView.CellFormatting eventhandler
private void dataGridView1_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
if (this.dataGridView1.Columns[e.ColumnIndex].Name.Equals("LapTime"))
{
var hundredSeconds = (int)e.Value;
var milliseconds = (double)(hundredSeconds * 10.0);
var timespan = TimeSpan.FromMilliseconds(milliseconds);
e.Value = timespan.ToString(#"mm\:ss\.fff");
// will produce 02:03.45
}
}
You can "subscribe" to this event in the constructor of your Form
public YourForm()
{
InitializeComponent();
RaceResults.CellFormattiing += dataGridView1_CellFormatting;
}
TimeSpan will help you do the job.
From your description, the time should be stored as milliseconds in your database.
So just do:
var ts = TimeSpan.FromMilliseconds(12345);
var timeStr = ts.ToString("HH:mm:ss");
You can custom date time format by changing "HH:mm:ss" to other formats. See Custom Date and Time Format Strings.

I want to retrieve the current date and time nox textBox

protected void ButtonPesquisar_Click(object sender, EventArgs e)
{
var macroController = new MacroController();
var itens = macroController.ObterTodos(new Entities.FiltroMacro()
{
//NumeroLocomotiva = TextBoxNumeroLocomotiva.Text,
DataInicio = DateTime.Parse(TextBoxDataInicio.Text + " " + TextBoxHoraInicio.Text),
DataFim = DateTime.Parse(TextBoxDataFim.Text + " " + TextBoxHoraFim.Text)
my code now works as follows: inform the values ​​in textBox and returns me what is posted. But I'm wanting to return the current date and time of the system without I need to fill.
This is very simple, you could have just Googled this.
TextBoxHora.Text = DateTime.Today.ToString("g"); // Just the time
TextBoxData.Text = DateTime.Today.ToString("D"); // Just the Date
TextBoxDataHora.Text = DateTime.Today.ToString(); // Complete date and Time
TextBoxDataHoraCompleta.Text = DateTime.Now;
Go to these links for more information.
Link
Link
In the code I saw that you want the get the date from the text boxes, so: If you want to parse the date time and provide the format in one string you should use the DateTime.ParseExact method. For instance, see the usage in a sample console application:
static void Main(string[] args)
{
var parsedDate = DateTime.ParseExact("2014$05$01", "yyyy$MM$dd", DateTimeFormatInfo.CurrentInfo);
Console.WriteLine("Year: {0}",parsedDate.Year);
Console.WriteLine("Month: {0}",parsedDate.Month);
Console.WriteLine("Day: {0}",parsedDate.Day);
Console.ReadLine();
}
You can read Standard Date and Time Format Strings at msdn for searching more information about the date formats.

C# program crash

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

How to get the selected date of a MonthCalendar control in C#

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

Dynamically changing of date

This Current Date and time, but I want to have time dynamically changeable like system Time:
DateTime t = DateTime.Now;
toolStripStatusLabel.Text = "Current Date:" + " " + t.ToString("MMMM dddd dd, yyyy")+" " +"current Time:" +" " +t.ToString("hh:mm ss tt");
On your winform, add a Timer Control and a Label Control.
In the Form Load Event add the code
yourTimer.Start();
In the Property sheet of the Timer Control, change the Interval Property to 1000.
Add the Timer Tick Event
private void yourTimer_Tick(object sender, EventArgs e)
{
yourLabel.Text = DateTime.Now.ToString("dd MMM yyyy hh:mm:ss");
}
My guess is that you want the ToolStripStatusLabel text to change with the time. For that, you'll need to have a timer callback. Add a Timer to your form and in its Elapsed handler, set the text to the current time, like you are already doing.
Else you can set the time once from the server side and keep changing the tooltip value from Javascript. In this case you don't have to go to the server side again and again :)
Just some more information
In your code:
DateTime t = DateTime.Now;
toolStripStatusLabel.Text = "Current Date:" + " "
+ t.ToString("MMMM dddd dd, yyyy")
+ " " + "current Time:"
+ " " + t.ToString("hh:mm ss tt");
The current date is evaluated only once.
That is to say, DateTime t = DateTime.Now stores the current date in t and this value is never updated again.
So even if you use 't' a hundred times, it will always have the value that was assigned to it.
Like astander pointed out, you need to update it every second or so.
A suggestion:
Instead of using "somestring" + "someotherstring" + "yetanotherstring" you should
use String.Format instead. For example (based on the code by astander)
private void yourTimer_Tick(object sender, EventArgs e)
{
yourLabel.Text = String.Format("Current Date: {0}",
DateTime.Now.ToString("dd MMM yyyy hh:mm:ss"));
}

Categories