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.
Related
I have the following code which takes the element in the lines array and checks if it matches the datetime format. This check only runs on elements 37, 38, 40, 41. Given the following code and debugging print outs I can see that the output does match the parsing. Why does it return false then?
Possible Inputs:
05/03/2005 23:59:59.999
05/3/2005 23:59:59.999
5/03/2005 23:59:59.999
5/3/2005 23:59:59.999
etc...
Code:
lines[i] = lines[i] + " 23:59:59.999"; //YYYY-MM-DDThh:mm:ss[.mmm]
DateTime datetest;
if (DateTime.TryParseExact(lines[i], "MM/dd/yyyy HH:mm:ss.mmm", new CultureInfo("en-US"), DateTimeStyles.None, out datetest))
{
}
else
{
//Log and Drop
logfile.WriteLine(System.DateTime.Now.ToString("yyyy.MM.dd.HH.mm.ss") + ": Row #" + row + ", Column #" + (i) + " was not a date in the right format, dropping line. ");
logfile.WriteLine("Original: " + lines[i]);
Console.WriteLine("Date Wrong");
Console.WriteLine("Date: " + lines[i]);
string input = Console.ReadLine();
continue;
}
Console Output:
Date Wrong
Date: 5/23/2004 23:59:59.999
UPDATE:
I tried changing the parse to look for M/dd/yyyy instead. However I now get this output instead.
Date Wrong
Date: 05/23/2005 23:59:59.999
UPDATE 2:
Ok I tried changing the parse to look for "M/d/yyyy HH:mm:ss.fff" as many suggested. The output I get now is:
Date Wrong
Date: 23.59.59.999
UPDATE 3:
Ok I have now tried "M/d/y H:m:s.fff" as suggested and I am still getting output as:
Date Wrong
Date: 05/23/2005 23:59:59.999
Note: Answer based on original revision of the question before it started morphing.
Why does it return false then?
The MM format requires two digits for the month. Your date string only has one digit. Use the M month format. The milliseconds format string should be fff rather than mmm.
The following format string will parse your input
M/dd/yyyy HH:mm:ss.fff
To demonstrate:
DateTime datetest;
Console.WriteLine(DateTime.TryParseExact("5/23/2004 23:59:59.999",
"M/dd/yyyy HH:mm:ss.fff", new CultureInfo("en-US"), DateTimeStyles.None,
out datetest));
which outputs
True
If you wish to allow for single digit months then you need d instead of dd. In order for you to proceed much further, you will need to work out exactly what format of dates you wish to support.
You have the wrong datetime format that you try to parse to. Change it to: "M/dd/yyyy HH:mm:ss.fff"
In response to the comment:
DateTime datetest;
var dateTimes = new [] { "05/03/2005 23:59:59.999", "05/3/2005 23:59:59.999", "5/03/2005 23:59:59.999", "5/3/2005 23:59:59.999" };
foreach(var dateTimeToParse in dateTimes)
if (DateTime.TryParse("5/3/2005 23:59:59.999", new CultureInfo("en-US"), DateTimeStyles.None, out datetest))
Console.WriteLine(dateTimeToParse + " parses to: " + datetest);
else
Console.WriteLine("FAIL!");
Works on my machine:
05/03/2005 23:59:59.999 parses to: 2005-05-03 23:59:59
05/3/2005 23:59:59.999 parses to: 2005-05-03 23:59:59
5/03/2005 23:59:59.999 parses to: 2005-05-03 23:59:59
5/3/2005 23:59:59.999 parses to: 2005-05-03 23:59:59
I can't see the contents of lines[I], but the mismatch between the format described in the comment and the format used in the TryParse may just be your issue:
lines[i] = lines[i] + " 23:59:59.999"; //YYYY-MM-DDThh:mm:ss[.mmm]
...
if (DateTime.TryParseExact(lines[i], "MM/dd/yyyy HH:mm:ss.mmm",
Using this (like already suggested Hans and David):
class Program
{
static void Main(string[] args)
{
List<String> datetimeList = new List<string>();
datetimeList.Add("05/03/2005 23:59:59.999");
datetimeList.Add("05/3/2005 23:59:59.999");
datetimeList.Add("5/03/2005 23:59:59.999");
datetimeList.Add("5/3/2005 23:59:59.999");
DateTime datetest;
foreach (string s in datetimeList)
{
if (!DateTime.TryParseExact(s, "M/d/yyyy HH:mm:ss.fff", new CultureInfo("en-US"), DateTimeStyles.None, out datetest))
{
Console.WriteLine("Error");
}
else
{
Console.WriteLine("Success");
}
}
Console.Read();
}
}
prints 4 times "Success" .
This only a proof of concept, i don't want any upvotes.
I am wondering if it possible to convert a Full Date and Day e.g.
Thursday 18th of April 2013
to a string (DD/MM/YYYY)
Yes check into Standard Date Time Format strings, and Custom Date Time Format strings
You can try using the DateTime.Parse(string str) method.
For example,
DateTime.Parse("Thu, 18 April 2013");
gives the following output,
04/18/2013 00:00:00
There may be an easier way, but here is a quick method that came to mind based upon my understanding of your question. There is a bit of extra code, so that you can add into a blank Windows form project and see the value.
String strEntry = #"Thursday 18th of April 2013";
DateTime dteValue = DateTime.MinValue;
strEntry = strEntry.Replace("of", null);
strEntry = strEntry.Replace("rd ", " ");
strEntry = strEntry.Replace("th", null);
strEntry = strEntry.Replace("st", null);
DateTime.TryParse(strEntry, out dteValue);
String strFormat = dteValue.ToString("dd/MM/yyyy");
MessageBox.Show(strFormat, "Date Value", MessageBoxButtons.OK);
below is my html code
<MKB:TimeSelector ID="TimeFrom" runat="server" DisplaySeconds="False">
</MKB:TimeSelector>
and a text box which is having a date.
VehicleBookingDate.Text
I want to save date and time in my database. for that if I want to do like below
string t1 = tsTimeFrom.Hour.ToString() + ":" + tsTimeFrom.Minute.ToString() + " " + tsTimeFrom.AmPm.ToString();
DateTime Time_From = Convert.ToDateTime(t1);
It saves time with current date, where as I want to save this time with this date which is in VehicleBookingDate.Text.
how can I do that.
// use a string formatter to pull it all together
string s = string.Format("{0} {1}:{2} {3}",
VehicleBookingDate.Text,
tsTimeFrom.Hour,
tsTimeFrom.Minute,
tsTimeFrom.AmPm);
// You can parse it this way, which will assume the current culture settings
DateTime Time_From = DateTime.Parse(s);
// Or you can be much more specific - which you probably should do.
DateTime Time_From = DateTime.ParseExact(s,
"d/M/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);
You may want to use a specific culture instead if you know it.
Be aware that date formats vary significantly by culture. For example, the value 1/4/2013 could be interpreted as either January 4th or April 1st depending on what part of the world you are in. You either need to be culture aware, or you need to explicitly tell your user what format to use.
I have a custom DateTime format string: "M/d/yyyy h:m:ss tt".
For example, with the date 'September 18th, 2012 # noon', I expect the output of this to be something like "9/18/2012 12:0:00 PM".
The time seems to be formatting properly, but the date portion is getting messed up. I am seeing the dates formatted as "MM-dd-yyyy" and I can't figure out why.
Here is some sample code to reproduce the problem:
var datetime = DateTime.Now;
Console.WriteLine("Date: " + datetime.ToString("MMMM d, yyyy")); // Date: October 11, 2012 --> correct
Console.WriteLine("Date: " + datetime.ToString("M/d/yyyy h:m:ss tt")); // Date: 10-11-2012 4:34:17 PM --> wrong
Here is the MSDN doc for custom DateTime format strings.
Any ideas on what am I doing wrong? How can I achieve my desired result?
Edit:
The thing that is incorrect in the last line of sample code is that there is hyphens instead of slashes and I don't know why.
Also, my computer's language is set to English (Canada). But neither my "short" nor "long" date format look like M-d-yyyy so I have no idea where that is coming from.
/ is the date separator, that is culture-dependant - in your current culture it is defined as -. If you want always a / use:
Console.WriteLine("Date: " + datetime.ToString("M\"/\"d\"/\"yyyy h:m:ss tt"));
or
Console.WriteLine("Date: " + datetime.ToString("M'/'d'/'yyyy h:m:ss tt"));
i.e. put the parts that you want to be output 'as is' inside quotes.
Try:
datetime.ToString("M/d/yyyy h:m:ss tt", CultureInfo.InvariantCulture);
Your culture might be overriding your date separator.
This article explains how the current culture can change the output of DateTime.ToString(string). Read the section that contains this text:
This method uses formatting information derived from the current
culture
This article explains how to get/set the culture so that you can test this possibility.
This article explains how you can explicitly provide DateTime.ToString with a culture to use.
Try the adding the invariant culture, Using the InvariantCulture Property
Console.WriteLine("Date: " + datetime.ToString("M/d/yyyy h:m:ss tt", CultureInfo.InvariantCulture));
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
var datetime = DateTime.Now;
Console.WriteLine("Date: " + datetime.ToString("MMMM d, yyyy"));
// Date: October 11, 2012 --> correct
Console.WriteLine("Date: " + datetime.ToString("M/d/yyyy h:m:ss tt"));
i'm currently working on a little project and i'm stuck with a little problem.
I would like my program to call a method CheckDate on boot.
This method would read in a .txt file to see the last saved date in (yyyy/mm/dd) format.
Then it would compare it with todays date and if it's not the same go on with some instructions.I've read the doc here but can't quite find which method best suites my need.
Question 1: Is there a way to get today's date in (yyyy/mm/dd) format?
Question 2: What's the easiest way to compare Dates in C#?
Thanks in advance.
1. DateTime.Now.ToString("yyyy/MM/dd")
2. DateTime.Parse(input).Date == DateTime.Now.Date
You can get today's date as a string by simply formatting a date.
String today = String.Format("{0: yyyy/MM/dd}", DateTime.Now);
String today = DateTime.Now.ToString("yyyy/MM/dd");
I would advise against using a text file as your means of saving data but if you are going with that system the only thing you would have to do is check to see if the date from the text file matches the date you formatted. Simply comparing formatted strings should do the trick.
if (string a == string b)
You could even put it in one line without having to format stuff separately
if (DateTime.Now.ToString("yyyy/MM/dd").Equals("date pulled from txt file"))
What's the easiest way to compare Dates in C#?
Store them not as text but in a DatteTime.
Compare the variables.
If there is a time in both, compare a.Date == b.Date.
Is there a way to get today's date in (yyyy/mm/dd) format?
Yes. This is wrong, though. PARSE The wrong input and compare the parsed data.
There is a DateTime.Compare method that you could use http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx - this should also let you use the built-in < and > operators.
By the letter of the question:
1:
DateTime.Now.ToString(#"yyyy\/MM\/dd")
2:
if(d1 < d2)...
if(d2 >= d1)...
etc.
However.
DateTime dt;
if(DateTime.TryParseExact(readInString, "yyyy-MM-dd", null, DateTimeStyles.AssumeLocal, out dt))
{
if(dt != DateTime.Now.Date)
{
//Code for case where it's no longer that day goes here.
}
}
else
{
//Code for someone messed up the file and it's not a valid date any more goes here.
}
You're doing this for computer-reading, not human-reading, so use the standard format rather than the conventional format (standard as in ISO, but also every country except North Korea has it as the national standard): yyyy-MM-dd (Edit: I see you're in Canada, CSA Z234.5:1989 is the relevant national standard on date-times for technical purposes; it says to use yyyy-MM-dd).
You should do it the other way around, read the string, parse the date, and do the comparison.
you might want to have a look at the FileInfo-Class ... you can compare the LastWriteTime Member to DateTime.Today
DateTime d1 = DateTime.Now;
DateTime d2 = d1.AddMilliseconds(123456789);
string formattedDate = d1.ToString("yyyy/MM/dd");
TimeSpan ts = d2 - d1;
double dayDiff = ts.TotalDays;
double hourDiff = ts.TotalHours;
double minuteDiff = ts.TotalMinutes;
double secondDiff = ts.TotalSeconds;
double milDiff = ts.TotalMilliseconds;
Console.WriteLine("Formatted Date: {0}\r\nDate Diff:\r\nTotal Days: {1}; Total Hours: {2}; Total Minutes: {3}; Total Seconds: {4}; Total Milliseconds: {5}", formattedDate,dayDiff,hourDiff,minuteDiff,secondDiff,milDiff);
Output:
Formatted Date: 2011/12/15
Date Diff:
Total Days: 1.42889802083333; Total Hours: 34.2935525; Total Minutes: 2057.61315; Total Seconds:
123456.789; Total Milliseconds: 123456789
*Edited my initial post to clarify how the "Total" properties work.
//use a TimeSpan do something like this
strCurDate = string.Format(DateTime.Now.ToString(), "yyyy/mm/dd");
FileInfo fiUpdateFileFile = null;
fiUpdateFileFile = new FileInfo(YourFile Location + Your FileName);
if (((TimeSpan)(DateTime.Now - fiUpdateFileFile.LastWriteTime)).TotalHours < 24)
{
// do your logic here...
}
// you could also get at DateTime.Now.Date() or Day.. depending on what you want to do