I'm working on formatting datetime's to display on a graph, and its working great so far. I have the format string:
M/dd/yyyy HH:mm:ss
and it prints as I'd like it to except the following: I want to completely hide the HH:mm:ss if the time is midnight.
Is it possible to do without a custom iformatprovider?
Thanks!
DateTime time = DateTime.Now;
string txt = time.ToString(time == time.Date ? "M/dd/yyyy" : "M/dd/yyyy HH:mm:ss");
DateTime time = DateTime.Now;
string format = "";
if (time.Hour == 0)
{
format = "M/dd/yyyy";
}
else
{
format = "M/dd/yyyy HH:mm:ss";
}
A culture-independent version of the solution proposed by #JDunkerley would be:
DateTime time = DateTime.Now;
string txt = time.ToString(time == time.Date ? "d" : "g");
More about standard date and time format strings here.
The proposed solution is not a very good one because it does not take into account user's localized time format, and simply assumes US English.
Here's how it should've been done:
public static string formatDateTimeWithTimeIfNotMidnight(DateTime dt)
{
//RETURN:
// = String for 'dt' that will have time only if it's not midnight
if (dt != dt.Date)
{
//Use time
return dt.ToString();
}
else
{
//Only date
return dt.ToShortDateString();
}
}
Related
My Problem: I want to convert an german date "24.05.05" to the UTC-Format "2005-05-24". In German date format "24.05.05" the last two digits is the year 2005.
Here is my code which not works:
var lGermanDate = "24.05.05";
DateTime lOutDateTime;
CultureInfo lCultureInfo = new CultureInfo("de-de");
// expecting result to fail
if (DateTime.TryParseExact(lGermanDate, lCultureInfo.DateTimeFormat.ShortDatePattern, lCultureInfo, DateTimeStyles.None, out lOutDateTime))
{
var lTargetDate = lOutDateTime.ToString("yyyy-m-d");
}
else
{
[...]
}
Note: in PHP this works with the following code:
\DateTime::createFromFormat('d.m.y', $lGermanDate )->format('Y-m-d');
Have you try the following?
//To Convert lGermanDate into DateTime
string DATEPATTERN = "dd.MM.yy";
DateTime.TryParseExact(lGermanDate, DATEPATTERN, null, DateTimeStyles.None, out DateTime outGermanDate);
//From outGermanDate to UTC Format
string dateUTC = outGermanDate.ToString("yyyy-MM-dd")
Your parsing is fine, maybe a little too specific
m is minutes is DateTime.ToString() patterns, M is month
var germanDateStr = "24.05.05";
if (DateTime.TryParse(germanDateStr, out DateTime outDateTime))
{
var targetDate = outDateTime.ToString("yyyy-M-d");
targetDate.Dump();
}
else
{
}
My system time is of the format dd-MMM-yy (02-Dec-16). The format I want to convert it to is "yyyy/MM/dd". I've basically been playing around with all the other datetime formats that my system offers and this is the parsing statement I've figured out that works for All of them (except this) -
CultureInfo provider = CultureInfo.InvariantCulture;
string date_format = "yyyy/MM/dd HH:mm:ss tt";
DateTime now_value = DateTime.ParseExact(DateTime.Now.ToString(date_format), date_format, provider);
return now_value.ToString(date_format);
But this doesn't work for the aforementioned dd-MMM-yy format. Can someone please tell me what I am doing wrong here?
(Sidebar -Is there a more efficient way in which I can write this above snippet?)
You don't need to convert DateTime to string and then convert back to DateTime and again back to string, if you have DateTime input just call the ToString with the format as below
string dt =DateTime.Now.ToString("yyyy/MMM/dd", CultureInfo.InvariantCulture);
for your example :
DateTime now_value = DateTime.ParseExact("02-Dec-16", "dd-MMM-yy", System.Globalization.CultureInfo.InvariantCulture);
return now_value.ToString("yyyy/MM/dd");
Try This:
string date_format = "yyyy-MMM-dd";
string date_now = DateTime.Now.ToString(date_format,CultureInfo.CreateSpecificCulture("en-US"));
return date_now;
Even This should also work:
string date_format = "yyyy-MMM-dd";
string date_now = DateTime.Now.ToString(date_format);
return date_now;
I think best way would be to create an extension method for multiple date formats,
var inputDate = "02-Dec-2016";
string[] availaible_input_date_format = { "dd-MMM-yyyy", "dd/MMM/yyyy" }; // add as many formats availible
var date_format = "yyyy/MMM/dd";
DateTime outputDate;
DateTime.TryParseExact(inputDate, availaible_input_date_format, null, DateTimeStyles.None, out outputDate);
Console.WriteLine(outputDate.ToString(date_format));
You can try this:
datetime yourdatetime = new datetime();
string converteddatetime = yourdatetime.toString("yyyy/MM/dd");
I am trying to convert a datatime string "including milliseconds" into a DataTime. I tried tried to use DateTime.TryParseExact but it does not give me a milliseconds.
Here is what I have tired
public static DateTime? dateTimeVal(string raw, string format = null)
{
DateTime final;
if(raw != null){
if( format != null){
string[] formats = new[] { format };
if (DateTime.TryParseExact(raw, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out final))
{
return final;
}
}
if (DateTime.TryParse(raw, out final))
{
return final;
}
}
return null;
}
This is how I use the method above
DateTime? dt = dateTimeVal("2016-03-14 11:22:21.352", "yyyy-MM-dd HH:mm:ss.fff");
However, dt gives me this 3/14/2016 11:22:21 AM
How can I get the value to include the milliseconds?
DateTime final = new DateTime();
var test = DateTime.TryParseExact("2016-03-14 11:22:21.352", new string[] { "yyyy-MM-dd HH:mm:ss.fff" }, CultureInfo.InvariantCulture, DateTimeStyles.None, out final);
This works for me.
Just take care for your fff. If you write them uppercase, the milliseconds will be supressed. Lowercase they will be parsed.
The only thing away from that I can imagine is you have used .ToString without providing any format. Then you'll get:
Are you sure you've written the providing format lowercase inside your code? Also have you used .ToString() with an output-format that shows up the milliseconds?
If you want to get the DateTime as string with milisecond, then you can use the following code;
string dateTime = dt.Value.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
Hope this helps.
I have a program that has synchronization. That means I need to save the last synchronization date and check if it needs to be synchronized.
So, I have this:
IS.SaveContactsRetrieveDate(DateTime.Now.ToString("dd.MM.yyyy"));
Saving a date to Isolated Storage.
Then, when I call IF:
DateTime toDate = DateTime.Now;
string contactsRetriveDate = IS.ReadContactsRetriveDate();
if (contactsRetriveDate == "" || DateTime.Compare(toDate, DateTime.Parse(contactsRetriveDate)) == 1)
{
MessageBox.SHow("");
}
The problem is that when user changes the region code fails here:
DateTime.Compare(toDate, DateTime.Parse(contactsRetriveDate))
With incorrect input error.
I understand that Latvian format is dd.MM.yyyy and USA MM/dd/yyyy - but I can't find a solution...
I need all datetime parsed in one format, so I could add days, weeks and compare date.
You should serialize and deserialize your date in a culture-independent manner (where "d" is the "Short date pattern" of the Standard Date and Time Format Strings):
var s = DateTime.Now.ToString("d", CultureInfo.InvariantCulture);
var d = DateTime.Parse(s, CultureInfo.InvariantCulture);
You can use ParseExact
DateTime.ParseExact(datestring, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
you already know format so you can go for this, but make sure the string is in same format and never changes.
u can try this one:
DateTime toDate = DateTime.Now;
string contactsRetriveDate = IS.ReadContactsRetriveDate();
DateTime contactsRetriveDat = Convert.ToDateTime(contactsRetriveDate);
if (contactsRetriveDate == "" || toDate.CompareTo(contactsRetriveDat)==0)
{
MessageBox.SHow("");
}
In C# / Winform, I'm able to parse a string to a date if the user input: dd/mm/yyyy
DateTime.Parse(date).ToString();
I would like to be able to parse without the slash (like in a datagridview or a DateTimePicker for example).
01022012 should be parsed to 01/02/2012
Anyone know how to parse it with DateTime.Parse?
Here is my code :
private void dataGridView_BadgeService_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (dataGridView_BadgeService.Columns[e.ColumnIndex].Name == "DateDebut" || dataGridView_BadgeService.Columns[e.ColumnIndex].Name == "DateFin")
{
string date = Convert.ToString(e.FormattedValue).Trim();
if (date.Length > 0)
{
try
{
DateTime _date;
DateTime.TryParseExact(date, "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out _date);
date = _date.ToShortDateString();
dataGridView_BadgeService.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = date;
}
catch
{
MessageBox.Show("Merci de saisir une date, ou laissez cette zone vierge", "Action-Informatique", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
e.Cancel = true;
}
}
}
}
Here is the Exception Message :
It says that : "System.FormatException: The string is not recognized as a DateTime valide"
Try with something like this...
string unslashedValue = "01022012"
DateTime date;
DateTime.TryParseExact(unslashedValue, "ddMMyyyy",
CultureInfo.InvariantCulture, DateTimeStyles.None, date);
... and, with date variable, you only need to...
string slashedValue = date.ToString("dd/MM/yyyy");
HuorSwords isn't wrong (other than the use of string as the input value), but the answer doesn't strictly answer the question: in order to display the date as requested, you need to format to a string after the fact:
DateTime date = DateTime.ParseExact(input,
"ddMMyyyy", CultureInfo.InvariantCulture);
string formattedDate = date.ToString("dd/MM/yyyy");
That seems like an awful lot of work when you could do something as simple as the two examples below. Date and time can be formatted using predefined formats and also user-defined formats.
This is a link to a brief video demonstrating both uses from a text editing program I'm designing.
https://od.lk/s/MTRfMjY2NzQxODVf/2022-03-20-20-55-52.mp4
This link will certainly get you on the right track:
https://www.vbtutor.net/vb2008/vb2008_lesson16.html
'Declaration (If you wish to use SpeechSynthesizer)
Private Ethro As SpeechSynthesizer = New SpeechSynthesizer()
Ethro.SpeakAsync(Format(Now, "Long Date"))
'Or a simple MsgBox:
MsgBox(Format(Now, "Long Date"))