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"));
}
Related
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.
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 made 2 radiobuttons so the user can choose if he/she wants to view the time on a 24h format or a 12h format, this is the code I have on the timer:
var format = rad24h.Checked ? "HH:mm" : "hh:mm:ss tt";
timer1.Interval = 500;
DateTime myDateTime = DateTime.Now;
label1.Text = string.Format("Hora actual {0}\n ", myDateTime.ToString(format));
lblHK.Text = string.Format("Hong Kong {0}\n ", myDateTime.AddHours(7).ToString(format));
lblNY.Text = string.Format("Nova Iorque {0}\n ", myDateTime.AddHours(-5).ToString(format));
lblUkr.Text = string.Format("Ucrânia {0}\n", myDateTime.AddHours(2).ToString(format));
lblTay.Text = string.Format("Taymyrskiy {0}\n ", myDateTime.AddHours(3).ToString(format));
lblAla.Text = string.Format(" Alaska {0}\n", myDateTime.AddHours(-9).ToLongString(format));
lblUru.Text = string.Format("Uruguay {0}\n", myDateTime.AddHours(-4).ToString(format));
lblSyd.Text = string.Format(" Sydney {0}\n", myDateTime.AddHours(9).ToString(format));
lblMad.Text = string.Format("Madagascar {0}\n ", myDateTime.AddHours(2).ToString(format));
The only label that does work with this is the lblUkr, (fourth from top-down)...
I've checked everything on the other lines to ensure they are the same, what I'm I missing?
Also, the label does not show AM/PM... how can I do this?
UPDATE
Actually, I noticed something weird... the first time I tried the code I did it only on lblUkr, and it was working, then I changed the position of the radio buttons, put the 24h one on top and made it already selected, but when I debug it goes down and none is selected... I assume that somehow, when it debugs it does not update on what I am doing on the application... any ideas what could be wrong?
UPDATE 2
It does work now, I had to re-save the project and change some things and all and it now works, but still, there is no AM, PM text on the end of the clocks, do I need to do it myself or is there a code to it?
It's working fine for me. Not sure what the problem is.
Make sure you actually start your timer, and that you've bound your code to run on the Tick event...
To check that it was "working fine", I converted your sample to look like this:
var format = false ? "HH:mm" : "hh:mm:ss tt";
DateTime myDateTime = DateTime.Now;
Console.WriteLine(string.Format("Hora actual {0}\n ", myDateTime.ToString(format)));
Console.WriteLine(string.Format("Hong Kong {0}\n ", myDateTime.AddHours(7).ToString(format)));
Console.WriteLine(string.Format("Nova Iorque {0}\n ", myDateTime.AddHours(-5).ToString(format)));
Console.WriteLine(string.Format("Ucrânia {0}\n", myDateTime.AddHours(2).ToString(format)));
Console.WriteLine(string.Format("Taymyrskiy {0}\n ", myDateTime.AddHours(3).ToString(format)));
Console.WriteLine(string.Format(" Alaska {0}\n", myDateTime.AddHours(-9).ToString(format)));
Console.WriteLine(string.Format("Uruguay {0}\n", myDateTime.AddHours(-4).ToString(format)));
Console.WriteLine(string.Format(" Sydney {0}\n", myDateTime.AddHours(9).ToString(format)));
Console.WriteLine(string.Format("Madagascar {0}\n ", myDateTime.AddHours(2).ToString(format)));
When you change var format = false ... to var format = true ..., then it switches from a 12 hour clock to a 24 hour clock. This is what you described, so that code is fine.
Maybe you should set a break point and check variables/see how many times your code gets called via the debugger...
The code you posted should work. Try calling .Invalidate() or .Refresh() for each of the labels to make sure they are redrawn. Also, I assume you are using a System.Windows.Forms.Timer so there is no cross-thread control access, right?
DateTime date1;
date1 = new DateTime(2008, 1, 1, 18, 9, 1);
Console.WriteLine(date1.ToString("hh:mm:ss tt",
CultureInfo.InvariantCulture));
// Displays 06:09:01 PM
and also you can use cultures for your countries alike
Console.WriteLine(date1.ToString("hh:mm:ss tt",
CultureInfo.CreateSpecificCulture("hu-HU")));
// Displays 06:09:01 du.
-- from MSDN
So you are using correct format, but try to make it alike this in OOP style :)
Check the format, the H is for 24 hour format, the h is for 12 hours.
and 'tt' for AM or PM.
How do you display the current date and time in a label in c#
You'd need to set the label's text property to DateTime.Now:
labelName.Text = DateTime.Now.ToString();
You can format it in a variety of ways by handing ToString() a format string in the form of "MM/DD/YYYY" and the like. (Google Date-format strings).
For time:
label1.Text = DateTime.Now.ToString("HH:mm:ss"); //result 22:11:45
or
label1.Text = DateTime.Now.ToString("hh:mm:ss tt"); //result 11:11:45 PM
For date:
label1.Text = DateTime.Now.ToShortDateString(); //30.5.2012
The System.DateTime class has a property called Now, which:
Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time.
You can set the Text property of your label to the current time like this (where myLabel is the name of your label):
myLabel.Text = DateTime.Now.ToString();
labelName.Text = DateTime.Now.ToString("dddd , MMM dd yyyy,hh:mm:ss");
Output:
If you want to do it in XAML,
xmlns:sys="clr-namespace:System;assembly=mscorlib"
<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now}}"
With some formatting,
<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now},
StringFormat='{}{0:dd-MMM-yyyy hh:mm:ss}'}"
DateTime.Now.Tostring();
. You can supply parameters to To string function in a lot of ways like given in this link
http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm
This will be a lot useful. If you reside somewhere else than the regular format (MM/dd/yyyy)
use always MM not mm, mm gives minutes and MM gives month.
In WPF you'll need to use the Content property instead:
label1.Content = DateTime.Now.ToString();
label1.Text = DateTime.Now.ToLongTimeString();//its for current date
label1.Text = DateTime.Now.ToLongDateString();//its for current time
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