Convert string to Time - c#

I have a time that is 16:23:01. I tried using DateTime.ParseExact, but it's not working.
Here is my code:
string Time = "16:23:01";
DateTime date = DateTime.ParseExact(Time, "hh:mm:ss tt", System.Globalization.CultureInfo.CurrentCulture);
lblClock.Text = date.ToString();
I want it to show in the label as 04:23:01 PM.

"16:23:01" doesn't match the pattern of "hh:mm:ss tt" - it doesn't have an am/pm designator, and 16 clearly isn't in a 12-hour clock. You're specifying that format in the parsing part, so you need to match the format of the existing data. You want:
DateTime dateTime = DateTime.ParseExact(time, "HH:mm:ss",
CultureInfo.InvariantCulture);
(Note the invariant culture, not the current culture - assuming your input genuinely always uses colons.)
If you want to format it to hh:mm:ss tt, then you need to put that part in the ToString call:
lblClock.Text = date.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);
Or better yet (IMO) use "whatever the long time pattern is for the culture":
lblClock.Text = date.ToString("T", CultureInfo.CurrentCulture);
Also note that hh is unusual; typically you don't want to 0-left-pad the number for numbers less than 10.
(Also consider using my Noda Time API, which has a LocalTime type - a more appropriate match for just a "time of day".)

string Time = "16:23:01";
DateTime date = DateTime.Parse(Time, System.Globalization.CultureInfo.CurrentCulture);
string t = date.ToString("HH:mm:ss tt");

This gives you the needed results:
string time = "16:23:01";
var result = Convert.ToDateTime(time);
string test = result.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);
//This gives you "04:23:01 PM" string
You could also use CultureInfo.CreateSpecificCulture("en-US") as not all cultures will display AM/PM.

The accepted solution doesn't cover edge cases.
I found the way to do this with 4KB script. Handle your input and convert a data.
Examples:
00:00:00 -> 00:00:00
12:01 -> 12:01:00
12 -> 12:00:00
25 -> 00:00:00
12:60:60 -> 12:00:00
1dg46 -> 14:06
You got the idea...
Check it https://github.com/alekspetrov/time-input-js

Related

Convert String to DateTime(yyyy-mm-dd)

I'm parsing date from server, date is in this format 6/16/2016 3:15:29 PM Could you help me please convert date to 2016-06-16?
I tried:
DateTime date = DateTime.ParseExact(datestring, "MM/dd/yyyy h-m-s t", System.Globalization.CultureInfo.InvariantCulture);
string formattedDate = date.ToString("yyyy-MM-dd")
but it's giving me error.
You've got 3 problems
You're not using the correct time separators
You're using only one t when you need two
You're using two M when you only need one
Try
DateTime date = DateTime.ParseExact(datestring, "M/d/yyyy h:m:s tt", System.Globalization.CultureInfo.InvariantCulture);
string formattedDate = date.ToString("yyyy-MM-dd");
The reason you need only one M is because MM expects a leading zero. Since the values of the date and time are delimited it's better to use the single versions for month, day, minutes, and seconds because they will work for values with or without leading zeros.
To execute DateTime.ParseExact() format of the input string and the format string must be the same. try this:
DateTime date = DateTime.ParseExact(datestring, "M/dd/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
string formattedDate = date.ToString("yyyy-MM-dd");
These are interesting in the given input string(6/16/2016 3:15:29 PM):
The month is represented in single digit so it should be M instead for MM. We use MM if it is specified as 06.
Same in the case of Hours too. It should be h instead for normal hh
There is a single space in between Date and Time as well as Time and PM.
So we must consider all of these while generating the Format-string for ParseExact

Datetime.parseExact gives (1-9) day's value with single digit, without 0

I have this code, it gives day's value as 1,2,3 .. instead of 01,02,03..
(DateTime.ParseExact("20160416", "yyyyMMdd", CultureInfo.InvariantCulture))
gives: 4/16/2016 12:00:00 AM.
I need 04/16/2016 12:00:00 AM
I have tried different cultures but nothing worked.
DateTime doesn't store any formatting information, it's just a structure representing a date and time. ParseExact is parsing your date string correctly.
If you want it formatted, you supply a format to DateTime.ToString, for example:
var formattedDate = dateTime.ToString("MM/dd/yyyy hh:mm:ss tt");
See this fiddle.
DateTime.ParseExact returns DateTime which doesn't have any implicit format. This "format" concept only applies when you get it's textual (a.k.a. string) representation.
You didn't told use how and where you see this 4/16/2016 12:00:00 AM string but if you wanna get days part with leading zero, you can use The dd format specifier with a proper culture (for calendar and time designators).
The dd custom format string represents the day of the month as a
number from 01 through 31. A single-digit day is formatted with a
leading zero.
DateTime dt = DateTime.ParseExact("20160416", "yyyyMMdd", CultureInfo.InvariantCulture);
string str = dt.ToString("MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
// 04/16/2016 12:00:00 AM

Datetime format Issue: String was not recognized as a valid DateTime

I want to format the input string into MM/dd/yyyy hh:mm:ss format in C#.
The input string is in format MM/dd/yyyy hh:mm:ss
For example :"04/30/2013 23:00"
I tried Convert.ToDateTime() function, but it considers 4 as date and 3 as month which is not what I want. Actually month is 04 and date is 03.
I tried DateTime.ParseExact() function also, But getting Exception.
I am getting error:
String was not recognized as a valid DateTime.
Your date time string doesn't contains any seconds. You need to reflect that in your format (remove the :ss).
Also, you need to specify H instead of h if you are using 24 hour times:
DateTime.ParseExact("04/30/2013 23:00", "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)
See here for more information:
Custom Date and Time Format Strings
You can use DateTime.ParseExact() method.
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format and culture-specific
format information. The format of the string representation must match
the specified format exactly.
DateTime date = DateTime.ParseExact("04/30/2013 23:00",
"MM/dd/yyyy HH:mm",
CultureInfo.InvariantCulture);
Here is a DEMO.
hh is for 12-hour clock from 01 to 12, HH is for 24-hour clock from 00 to 23.
For more information, check Custom Date and Time Format Strings
try this:
string strTime = "04/30/2013 23:00";
DateTime dtTime;
if(DateTime.TryParseExact(strTime, "MM/dd/yyyy HH:mm",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out dtTime))
{
Console.WriteLine(dtTime);
}
This can also be the problem if your string is 6/15/2019. DateTime Parse expects it to be 06/15/2019.
So first split it by slash
var dateParts = "6/15/2019"
var month = dateParts[0].PadLeft(2, '0');
var day = dateParts[1].PadLeft(2, '0');
var year = dateParts[2]
var properFormat = month + "/" +day +"/" + year;
Now you can use DateTime.Parse(properFormat, "MM/dd/yyyy"). It is very strange but this is only thing working for me.
change the culture and try out like this might work for you
string[] formats= { "MM/dd/yyyy HH:mm" }
var dateTime = DateTime.ParseExact("04/30/2013 23:00",
formats, new CultureInfo("en-US"), DateTimeStyles.None);
Check for details : DateTime.ParseExact Method (String, String[], IFormatProvider, DateTimeStyles)
DateTime dt1 = DateTime.ParseExact([YourDate], "dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
Note the use of HH (24-hour clock) rather than hh (12-hour clock), and the use of InvariantCulture because some cultures use separators other than slash.
For example, if the culture is de-DE, the format "dd/MM/yyyy" would expect period as a separator (31.01.2011).
Below code worked for me:
string _stDate = Convert.ToDateTime(DateTime.Today.AddMonths(-12)).ToString("MM/dd/yyyy");
String format ="MM/dd/yyyy";
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
DateTime _Startdate = DateTime.ParseExact(_stDate, format, culture);
You may use this type format (get formatted data from sql server)
FORMAT(convert(datetime,'16/04/2018 10:52:20',103),'dd/MM/yyyy HH:mm:ss', 'en-us')
CONVERT(VARCHAR,convert(datetime,'16/04/2018 10:52:20',103), 120)

Date and time format conversion in C#

I have date/time format, for example:
"2012-06-28T08:26:57Z"
What kind of date/time format is that and how can it be converted into the following format, using DateTime format in C#.:
"8/24/2012 4:09:17 AM"
You can do this:
string input = "2012-06-28T08:26:57Z";
var dt = DateTime.Parse(input);
string output = dt.ToString(#"MM/dd/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
For the meaning of each part of your input string, take a look at this link: http://www.w3.org/TR/NOTE-datetime
This is an ISO8601 date/time string. The numbers are the year, month, day, hour, minute, and second (in that order).
The "T" is a placeholder. It means nothing.
The "Z" is an indicator that the time is relative to GMT, rather than in a local time zone.
Try converting the date into string like this
date.ToString("yyyy-MM-dd HH':'mm':'ss")
Here date is a variable in which a date is present
or try this
string timeString = "11/12/2009 13:30:00.000";
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dateVal = DateTime.ParseExact(timeString, "dd/MM/yyyy HH:mm:ss.fff", culture);
These links might also be helpful to you.
DateTime.ToString() Patterns
String Format for DateTime [C#]
Try this to convert Universal datetime to local time
var date = DateTime.ParseExact("2012-08-25T06:57:57Z","yyyy-MM-ddTHH:mm:ssZ",System.Globalization.CultureInfo.CurrentCulture);
var newformat = date.ToString("MM/dd/yyyy HH:mm:ss tt");
try to use something liKe this.
var d = DateTime.Parse("2012-08-24T04:09:17Z");
Console.WriteLine (d.ToString("G"), CultureInfo.InvariantCulture);
Note that 'General date/time pattern (long time).' in .net is culture specific. From msdn:
6/15/2009 1:45:30 PM -> 6/15/2009 1:45 PM (en-US)
6/15/2009 1:45:30 PM -> 15/06/2009 13:45 (es-ES)
6/15/2009 1:45:30 PM -> 2009/6/15 13:45 (zh-CN)
That is Universal Sortable date format
You can use following code to convert it
var dt = DateTime.Parse("2012-06-28T08:26:57Z");
var newdt = String.Format("{0:G}", dt); // "6/28/2012 1:56:57 PM"
Update
You can try this also
var dt = DateTime.Parse("2012-06-28T08:26:57Z", System.Globalization.CultureInfo.InvariantCulture);
var newdt = String.Format("{0:G}", dt);
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx this is answer to your question. Here you can see how to create different date formats. According to this resource, you may use something like this:
String olddate="2012-06-28T08:26:57Z";
DateTime date=Convert.ToDateTime(olddate);
String date1=date.ToString("M/d/yyyy h:m:s tt");
you can simply use :)
DateTime dt = Convert.ToDateTime("2012-06-28T08:26:57Z");

How to convert timespan to pm or am time?

I'm storing user time in UTC time and when I show it I need to convert it to am pm time.
Here is example in database I have 17:00:00 convert to 5:00 pm
Here is the code what I came up so far but it's not working
var time = DateTime.ParseExact(object.Time.ToString(), "HHmm", CultureInfo.CurrentCulture).ToString("hh:mm tt");
var time = DateTime.ParseExact("17:00", "HH:mm", null).ToString("hh:mm tt");
returns 05:00 PM
DateTime.ParseExact is returning DateTime
Edited:
Include CultureInfo
var time = DateTime.ParseExact("17:00", "HH:mm", null).ToString("hh:mm tt", CultureInfo.GetCultureInfo("en-US"));
TimeSpan is a duration "17 hours", not a time. Maybe add this to a date (only) and use the existing datetime formatting options? (although watch for daylight savings)
i.e.
string s = DateTime.Today.Add(duration).ToString(specifier);
Don't forget to specify appropriate culture, e.g.: CultureInfo.InvariantCulture.
var time = DateTime.Now.ToString("h:mm tt", CultureInfo.InvariantCulture);
See also: Custom Date and Time Format Strings
I just needed to display static html with my TimeSpan. So in my view I used,
DateTime.Today.Add(StartTime).ToString("%h:mm tt")
"StartTime" is my TimeSpan, it converts it to a DateTime and then displays it. My time now displays as "3:00 PM" instead of "15:00". The "%h" eliminates a leading zero for time that is between 1-9.
Based on your comment, first convert the TimeSpan to a DateTime:
var dtUtc = DateTime.Now.ToUniversalTime();
dtUtc.AddHours(timeSpanObject.Hours);
dtUtc.AddMinutes(timeSpanObject.Minutes);
Once it's a DateTime, you can convert it from UTC to localtime:
var dtLocal = dtUtc.ToLocalTime();
Only when you display it would you include AM/PM, like:
dtLocal.ToString("h:mm tt");

Categories