I have a date/time return from a C# method is in string,
string dateTime = "2018-6-18 20:50:35"
Now I would like to convert this into another string representation like,
string convertDT = "2018-6-18 08:50:35 PM"
Is this possible?
Seems like I can do something like,
var formattedTime = dateTime.ToString("h:mm tt", CultureInfo.InvariantCulture);
but not working. Suggestion please!
Just parse the string into a new DateTime object and then call ToString() with the right formats:
string dateTime = "2018-6-18 20:50:35";
DateTime parsedDateTime;
if(DateTime.TryParse(dateTime, out parsedDateTime))
{
return parsedDateTime.ToString("yyyy-M-d hh:mm tt");
}
The benefit of my answer is that it contains validation (DateTime.TryParse()), it results in a couple extra lines of code but you can now accept all input and not worry about an exception being thrown.
Even better would be to refactor this logic into its own method that you can re-use:
public static bool TryChangeDateTimeFormat(string inputDateString, string outputFormat, out string outputDateString)
{
DateTime parsedDateTime;
if(DateTime.TryParse(inputDateString, out parsedDateTime))
{
outputDateString = parsedDateTime.ToString(outputFormat);
return true;
}
outputDateString = string.Empty;
return false;
}
This returns a bool of whether or not the conversion was successful and the out variable will be modified depending on the result.
Fiddle here
Without adding any validation,
var string24h = "2018-6-18 20:50:35";
var dateTime = DateTime.Parse(string24h);
var formattedTime = dateTime.ToString("h:mm tt", CultureInfo.InvariantCulture);
Use DateTime.ParseExact and then ToString
Sure, you can use the DateTime class to parse the original string and then output a differently formatted string for the same date:
string result = DateTime.Parse(dateTime).ToString("h:mm tt", CultureInfo.InvariantCulture);
var dateTime = "2018-6-18 20:50:35";
var dt = Convert.ToDateTime(dateTime);
var amPmDateTime = dt.ToString(#"yyyy-MM-dd hh:mm:ss tt", CultureInfo.InvariantCulture);
To give you exactly your format you would use
string convertDT = DateTime.Parse(dateTime).ToString("yyyy-MM-dd hh:mm:ss tt");
You can change the format between the quotes however you would like. For example yyyy/MM/dd or something. Just remember MM is 2 spots for months and mm is 2 spots for minutes.
So if you put
string convertDT = DateTime.Parse(dateTime).ToString("yyyy-mm-dd hh:mm:ss tt");
You are going to get year - minutes - days.
I've tried with several different format strings but I can't get it to parse a date like:
date = "10/16/13";
DateTime endDate = DateTime.ParseExact(date, "M-dd-yy", CultureInfo.InvariantCulture);
What am I missing?!
For it to parse the date your format needs to be the same. Change "M-dd-yy" to "M/dd/yy" Assuming that the month is a single digit and the day is always 2 digits.
Here you go this should work just fine. You just need to be aware that it will set a default time of 12:00 am because you are not specifying the time in your string.
class Program
{
static void Main(string[] args)
{
string date = "10/16/13";
//This is usually the safer way to go
DateTime result;
if(DateTime.TryParse(date, out result))
Console.WriteLine(result);
//I think this is what you were trying to accomplish
DateTime result2 = Convert.ToDateTime(date, CultureInfo.InvariantCulture);
Console.ReadKey();
}
}
i have textbox that accepts time format like this 12:40 PM but would like to convert it into time format like this 12:40:00 basically without the PM or AM. Here is what i have so far:
string StartTime = ((TextBox)TestDV.FindControl("txtBST")).Text.ToString();
thanks
One option would be to parse into a DateTime and then back to a string:
string s = "12:40 PM";
DateTime dt = DateTime.Parse(s);
string s2 = dt.ToString("HH:mm:ss"); // 12:40:00
Be aware, however, that most operations work better with a DateTime versus a string representation of a DateTime.
First you should parse it to a DateTime, then format it. It sounds like your input format is something like hh:mm tt and your output format is HH:mm:ss. So, you'd have:
string input = "12:40 PM"
DateTime dateTime = DateTime.ParseExact(input, "hh:mm tt",
CultureInfo.InvariantCulture);
string output = dateTime.ToString("HH:mm:ss", CultureInfo.InvariantCulture);
Note that:
I've used DateTime.ParseExact which will throw an exception if the parsing fails; you may want to use DateTime.TryParseExact (it depends on your situation)
I've used the invariant culture for both operations here. I don't know whether or not that's correct for your scenario.
I've used hh:mm, but you might want h:mm... would you expect "1 PM" or "01 PM"?
You don't parse seconds, so that part will always be 0... is that okay?
Since you are bringing it in as a string this is actually kind of easy.
string StartTime = ((TextBox)TestDV.FindControl("txtBST")).Text.ToString();
DateTime dt = new DateTime();
try { dt = Convert.ToDateTime(StartTime); }
catch(FormatException) { dt = Convert.ToDateTime("12:00 AM"); }
StartTime = dt.ToString("HH:mm");
So you bring in your string, and convert it to a date. if the input is not a valid date, this will default it to 00:00. Either way, it gives you a string and a DateTime object to work with depending on what else you need to do. Both represent the same value, but the string will be in 24-Hour format.
Cheers!!
Inside a function, I need to find the difference between 2 dates in seconds. If the difference is more than 30 seconds i return False otherwise it returns True , first one I read it from database and Second one is the current DateTime.Now
Here is the snippest of code I'm using that does the work while dr.GetValue(0).ToString() holds the current value in the database :
if (dr.Read())
{
DateTime nowDate = Convert.ToDateTime(DateTime.Now.ToString("M/dd/yyyy H:mm:ss tt"));
DateTime then = DateTime.ParseExact(dr.GetValue(0).ToString(), "M/dd/yyyy H:mm:ss tt", CultureInfo.InvariantCulture);
TimeSpan diff = nowDate - then;
int timeDifference = diff.Seconds;
if (timeDifference > 30)
{
myConn.Dispose();
return false;
}
else {
myConn.Dispose();
return true;
}
}
When i execute the code above i get a message error : string was not recognized as valid DateTime
And here is the line that is causing the error :
DateTime then = DateTime.ParseExact(dr.GetValue(0).ToString(), "M/dd/yyyy H:mm:ss tt", CultureInfo.InvariantCulture);
The time is stored in the database in this format : 2013-02-18 14:06:37
But when I execute the following line (for debugging purposes) :
MessageBox.Show(dr.GetValue(0).ToString());
I see a message box that shows the date in this format : 2/18/2013 2:06:37 PM
How to find the difference in seconds between the current time and the time stored in dr.GetValue(0).ToString()
Any help would be highly appreciated
You want h, not H. h is the hour in 12-hour format, H is the hour in 24-hour format. Since your example hour is 2 PM (not 14 PM) it's the 12-hour format you want.
Also:
You're converting your now-time to a string and back - don't bother!
You're counting Seconds not TotalSeconds - this is incorrect because e.g. a 60-second period gives a Seconds value of 0.
DateTime nowDate = DateTime.Now;
DateTime then = DateTime.ParseExact(
dr.GetValue(0).ToString(), "M/dd/yyyy h:mm:ss tt",
CultureInfo.InvariantCulture);
TimeSpan diff = nowDate - then;
double secondsDifference = diff.TotalSeconds;
You should even be able to do something along the lines of
DateTime then = dr.GetDateTime(0);
and avoid the string-parsing altogether, but the H/h difference is the reason you get the specific exception you asked about.
if, as it looks like, your date is a datetime in the database, you can probably simplify the two lines to this:
DateTime nowDate = DateTime.Now;
DateTime then = (DateTime)dr.GetValue(0);
(although I'm making a lot of assumptions here)
Your code really should be very simple:
if (dr.Read())
{
DateTime then = dr.GetDateTime(0);
TimeSpan diff = DateTime.Now - then;
int timeDifference = diff.TotalSeconds;
}
One thing to note - you really shouldn't be calling myConn.Dispose(); in your if/else. Wrap your connection and readers in a using statement.
I think your server has Application server has some other date format set. What you can try is this:
Convert.ToDate(value,System.Globalization.CultureInfo.GetCultureInfo("en-US").DateTimeFormate);
Hope this will solve the error.Haven't tested it so hope for best
I have a value stored in variable of type System.TimeSpan as follows.
System.TimeSpan storedTime = 03:00:00;
Can I re-store it in another variable of type String as follows?
String displayValue = "03:00 AM";
And if storedTime variable has the value of
storedTime = 16:00:00;
then it should be converted to:
String displayValue = "04:00 PM";
You can do this by adding your timespan to the date.
TimeSpan timespan = new TimeSpan(03,00,00);
DateTime time = DateTime.Today.Add(timespan);
string displayTime = time.ToString("hh:mm tt"); // It will give "03:00 AM"
Very simple by using the string format
on .ToSTring("") :
if you use "hh" ->> The hour, using a 12-hour clock from 01 to 12.
if you use "HH" ->> The hour, using a 24-hour clock from 00 to 23.
if you add "tt" ->> The Am/Pm designator.
exemple converting from 23:12 to 11:12 Pm :
DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("hh:mm tt"); // this show 11:12 Pm
var res2 = d.ToString("HH:mm"); // this show 23:12
Console.WriteLine(res);
Console.WriteLine(res2);
Console.Read();
wait a second, there is a catch, the system Culture !!, the same code executed on windows set to different language
especially with different culture language will generate different result.
for example in windows set to Arabic language the result Will be like this :
// 23:12 م
م means Evening (first letter of مساء) .
in windows set to German language i think it will show // 23:12 du.
you can change between different format on windows control panel under windows regional and language -> current format (combobox) and change... apply it, do a rebuild (execute) of your app and watch what i'm talking about.
so how can you force showing Am and Pm prefix in English event if the culture of the current system isn't set to English ?
easy just by adding two lines ->
the first step add using System.Globalization; on top of your code
and modify the previous code to be like this :
DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.InvariantCulture); // this show 11:12 Pm
InvariantCulture => using default English Format.
another question I want to have the pm to be in Arabic or specific language, even if I use windows set to English (or other language) regional format?
Solution for Arabic Exemple :
DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.CreateSpecificCulture("ar-AE"));
this will show // 23:12 م
event if my system is set to English region format.
you can change "ar-AE" if you want to another language format. there is a list for each language.
exemples :
ar ar-SA Arabic
ar-BH ar-BH Arabic (Bahrain)
ar-DZ ar-DZ Arabic (Algeria)
ar-EG ar-EG Arabic (Egypt)
.....
You can add the TimeSpan to a DateTime, for example:
TimeSpan span = TimeSpan.FromHours(16);
DateTime time = DateTime.Today + span;
String result = time.ToString("hh:mm tt");
Demo: http://ideone.com/veJ6tT
04:00 PM
Standard Date and Time Format Strings
Doing some piggybacking off existing answers here:
public static string ToShortTimeSafe(this TimeSpan timeSpan)
{
return new DateTime().Add(timeSpan).ToShortTimeString();
}
public static string ToShortTimeSafe(this TimeSpan? timeSpan)
{
return timeSpan == null ? string.Empty : timeSpan.Value.ToShortTimeSafe();
}
string displayValue="03:00 AM";
This is a point in time , not a duration (TimeSpan).
So something is wrong with your basic design or assumptions.
If you do want to use it, you'll have to convert it to a DateTime (point in time) first. You can format a DateTime without the date part, that would be your desired string.
TimeSpan t1 = ...;
DateTime d1 = DateTime.Today + t1; // any date will do
string result = d1.ToString("hh:mm:ss tt");
storeTime variable can have value like
storeTime=16:00:00;
No, it can have a value of 4 o'clock but the representation is binary, a TimeSpan cannot record the difference between 16:00 and 4 pm.
You will need to get a DateTime object from your TimeSpan and then you can format it easily.
One possible solution is adding the timespan to any date with zero time value.
var timespan = new TimeSpan(3, 0, 0);
var output = new DateTime().Add(timespan).ToString("hh:mm tt");
The output value will be "03:00 AM" (for english locale).
You cannot add AM / PM to a TimeSpan. You'll anyway have to associate the TimaSpan value with DateTime if you want to display the time in 12-hour clock format.
TimeSpan is not intended to use with a 12-hour clock format, because we are talking about a time interval here.
As it says in the documentation;
A TimeSpan object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date. Otherwise, the DateTime or DateTimeOffset structure should be used instead.
Also Microsoft Docs describes as follows;
A TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optional minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second.
So in this case, you can display using AM/PM as follows.
TimeSpan storedTime = new TimeSpan(03,00,00);
string displayValue = new DateTime().Add(storedTime).ToString("hh:mm tt");
Side note :
Also should note that the TimeOfDay property of DateTime is a TimeSpan, where it represents
a time interval that represents the fraction of the day that has elapsed since midnight.
To avoid timespan format limitations, convert to datetime.
Simplest expression would be:
// Where value is a TimeSpan...
(new DateTime() + value).ToString("hh:mm tt");
Parse timespan to DateTime and then use Format ("hh:mm:tt"). For example.
TimeSpan ts = new TimeSpan(16, 00, 00);
DateTime dtTemp = DateTime.ParseExact(ts.ToString(), "HH:mm:ss", CultureInfo.InvariantCulture);
string str = dtTemp.ToString("hh:mm tt");
str will be:
str = "04:00 PM"
You can try this:
string timeexample= string.Format("{0:hh:mm:ss tt}", DateTime.Now);
you can remove hh or mm or ss or tt according your need
where
hh is hour in 12 hr formate,
mm is minutes,ss is seconds,and tt is AM/PM.
Parse timespan to DateTime. For Example.
//The time will be "8.30 AM" or "10.00 PM" or any time like this format.
public TimeSpan GetTimeSpanValue(string displayValue)
{
DateTime dateTime = DateTime.Now;
if (displayValue.StartsWith("10") || displayValue.StartsWith("11") || displayValue.StartsWith("12"))
dateTime = DateTime.ParseExact(displayValue, "hh:mm tt", CultureInfo.InvariantCulture);
else
dateTime = DateTime.ParseExact(displayValue, "h:mm tt", CultureInfo.InvariantCulture);
return dateTime.TimeOfDay;
}
At first, you need to convert time span to DateTime structure:
var dt = new DateTime(2000, 12, 1, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds)
Then you need to convert the value to string with Short Time format
var result = dt.ToString("t"); // Convert to string using Short Time format
Because this situation is as annoying as it is common... I created a helper class, which I have released in a NuGet package. This could be a private method and can be used in MVC views as well as in back-end C# code.
public static string AsTimeOfDay(TimeSpan timeSpan, TimeSpanFormat timeSpanFormat = TimeSpanFormat.AmPm)
{
int hours = timeSpan.Hours;
int minutes = timeSpan.Minutes;
string AmOrPm = "AM";
string returnValue = string.Empty;
if (timeSpanFormat == TimeSpanFormat.AmPm)
{
if (hours >= 12)
{
AmOrPm = "PM";
}
if (hours > 12)
{
hours -= 12;
}
TimeSpan timeSpanAmPm = new TimeSpan(hours, minutes, 0);
returnValue = timeSpanAmPm.ToString(#"h\:mm") + " " + AmOrPm;
}
else
{
returnValue = timeSpan.ToString(#"h\:mm");
}
return returnValue;
}