How to convert timespan to pm or am time? - c#

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");

Related

I want to convert date "2018-05-18 17:16:24.570" to "7/26/2018, 10:42 AM" format in C#

I am retrieving the date as a string from the database and then need to convert it. So that prints in a different format.
I am using
string date = dr[2].ToString();
date = DateTime
.ParseExact(date,"yyyy-MM-dd hh:mm:ss.fff tt ",new CultureInfo.InvariantCulture("enUS"));
But this does not work:
System.FormatException: 'String was not recognized as a valid
DateTime.'
If you work with string you can put ParseExact followed by ToString:
string date = "2018-05-18 17:16:24.570";
// 5/18/2018 05:16 PM
date = DateTime
.ParseExact(date, "yyyy-M-d H:m:s.fff", CultureInfo.InvariantCulture)
.ToString("M/dd/yyyy hh:mm ttt", CultureInfo.GetCultureInfo("en-US"));
However, it seems you are working with DataReader (dr[2] fragment); if it's your case, Convert is a better option than ParseExact (providing that RDBMS has corresponding Date field):
string date = Convert
.ToDateTime(dr[2])
.ToString("M/dd/yyyy hh:mm ttt", CultureInfo.GetCultureInfo("en-US"));
Edit: If you want to change time from UTC to a TimeZone you can try TimeZoneInfo (see all available Time Zones here) e.g.
//TODO: Put the right Time Zone Id here
// Or should it be "Arabian Standard Time"? I've tried to guess
TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById("Atlantic Standard Time");
string date = TimeZoneInfo
.ConvertTimeFromUtc(Convert
.ToDateTime(dr[2]), zone)
.ToString("M/dd/yyyy hh:mm ttt", CultureInfo.GetCultureInfo("en-US"));

Convert string to Time

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

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");

Conversion to Time 12 hour Format From String containing Time in 24 hour format

I have a varchar(5) column in a table which contains the hour and minutes in 24 hour format time. I want to convert this 24 hour format to 12 hour format and finally embed this 12 hour format time into a DateTime Variable along with a Date value. Below is an example of demonstration.
For Example
8:18 should be converted into 8:18:00 AM and then should be embedded
with a Date like 8/10/2012 8:18:50 AM to be able to store in DateTime
column of DB.
22:20......10:20:00 PM.......8/10/2012 10:20:00 PM
The Date will not be current date it can be any date value like 8/8/2012 or 7/8/2012
You can do something like this:
string input = "22:45";
var timeFromInput = DateTime.ParseExact(input, "H:m", null, DateTimeStyles.None);
string timeIn12HourFormatForDisplay = timeFromInput.ToString(
"hh:mm:ss tt",
CultureInfo.InvariantCulture);
var timeInTodayDate = DateTime.Today.Add(timeFromInput.TimeOfDay);
And now the important parts to take in consideration:
The format for parsing uses "H:m" so it assumes a 24H value that does not use a zero to prefix single digits hours or minutes;
The format for printing uses "hh:mm:ss tt" because it seems to be the format you desire, however you need to use CultureInfo.InvariantCulture to be certain that you get a AM/PM designator that is in fact AM or PM. If you use another culture, the AM/PM designator may change;
The full date and time is constructed based on DateTime.Today which returns the today date with a zeroed time and then we just add the time we read from input.
To create the final date and time from another date you can instead use:
var timeInAnotherDate = new DateTime(2000, 1, 1).Add(timeFromInput.TimeOfDay);
Reference material:
DateTime Structure;
Custom Date and Time Format Strings;
Standard DateTime Format Strings.
create function dbo.COMBINE_DATE_TIME(
#DatePart DateTime, -- DateTime
#TimePart varchar(5)) -- Time
returns DateTime
as begin
return DATEADD(day, DATEDIFF(day,0,#DatePart),
CONVERT(DateTime,ISNULL(#TimePart,''),14))
end
go
string strDate = DateTime.ParseExact("8:18","HHmm",CultureInfo.CurrentCulture).ToString("hh:mm tt");
string fromTime = Convert.ToStr(reader["TimeFrom"]);
string toTime = Convert.ToStr(reader["TimeTo"]);
item.Time=DateTime.Parse(fromTime,CultureInfo.CurrentCulture).ToString("hh:mm tt");
here the property of your model(item.Time here) should be the string.

how to convert 24-hour format TimeSpan to 12-hour format TimeSpan?

I have TimeSpan data represented as 24-hour format, such as 14:00:00, I wanna convert it to 12-hour format, 2:00 PM, I googled and found something related in stackoverflow and msdn, but didn't solve this problem, can anyone help me? Thanks in advance.
Update
Seems that it's possible to convert 24-hour format TimeSpan to String, but impossible to convert the string to 12-hour format TimeSpan :(
But I still got SO MANY good answers, thanks!
(Summing up my scattered comments in a single answer.)
First you need to understand that TimeSpan represents a time interval. This time interval is internally represented as a count of ticks an not the string 14:00:00 nor the string 2:00 PM. Only when you convert the TimeSpan to a string does it make sense to talk about the two different string representations. Switching from one representation to another does not alter or convert the tick count stored in the TimeSpan.
Writing time as 2:00 PM instead of 14:00:00 is about date/time formatting and culture. This is all handled by the DateTime class.
However, even though TimeSpan represents a time interval it is quite suitable for representing the time of day (DateTime.TimeOfDay returns a TimeSpan). So it is not unreasonable to use it for that purpose.
To perform the formatting described you need to either rely on the formatting logic of DateTime or simply create your own formatting code.
Using DateTime:
var dateTime = new DateTime(timeSpan.Ticks); // Date part is 01-01-0001
var formattedTime = dateTime.ToString("h:mm tt", CultureInfo.InvariantCulture);
The format specifiers using in ToString are documented on the Custom Date and Time Format Strings page on MSDN. It is important to specify a CultureInfo that uses the desired AM/PM designator. Otherwise the tt format specifier may be replaced by the empty string.
Using custom formatting:
var hours = timeSpan.Hours;
var minutes = timeSpan.Minutes;
var amPmDesignator = "AM";
if (hours == 0)
hours = 12;
else if (hours == 12)
amPmDesignator = "PM";
else if (hours > 12) {
hours -= 12;
amPmDesignator = "PM";
}
var formattedTime =
String.Format("{0}:{1:00} {2}", hours, minutes, amPmDesignator);
Admittedly this solution is quite a bit more complex than the first method.
TimeSpan represents a time interval not a time of day. The DateTime structure is more likely what you're looking for.
You need to convert the TimeSpan to a DateTime object first, then use whatever DateTime format you need:
var t = DateTime.Now.TimeOfDay;
Console.WriteLine(new DateTime(t.Ticks).ToString("hh:mm:ss tt"));
ToShortTimeString() would also work, but it's regional-settings dependent so it would not display correctly (or correctly, depending on how you see it) on non-US systems.
TimeSpan represents a time interval (a difference between times),
not a date or a time, so it makes little sense to define it in 24 or 12h format. I assume that you actually want a DateTime.
For example 2 PM of today:
TimeSpan ts = TimeSpan.FromHours(14);
DateTime dt = DateTime.Today.Add(ts);
Then you can format that date as you want:
String formatted = String.Format("{0:d/M/yyyy hh:mm:ss}", dt); // "12.4.1012 02:00:00" - german (de-DE)
http://msdn.microsoft.com/en-us/library/az4se3k1%28v=vs.100%29.aspx
Try This Code:
int timezone = 0;
This string gives 12-hours format
string time = DateTime.Now.AddHours(-timezone).ToString("hh:mm:ss tt");
This string gives 24-hours format
string time = DateTime.Now.AddHours(-timezone).ToString("HH:mm:ss tt");
Assuming you are staying in a 24 hour range, you can achieve what you want by subtracting the negative TimeSpan from Today's DateTime (or any date for that matter), then strip the date portion:
DateTime dt = DateTime.Today;
dt.Subtract(-TimeSpan.FromHours(14)).ToShortTimeString();
Yields:
2:00 PM
String formatted = yourDateTimeValue.ToString("hh:mm:ss tt");
It is very simple,
Let's suppose we have an object ts of TimesSpan :
TimeSpan ts = new TimeSpan();
and suppose it contains some value like 14:00:00
Now first convert this into a string and then in DateTime
as following:
TimeSpan ts = new TimeSpan(); // this is object of TimeSpan and Suppose it contains
// value 14:00:00
string tIme = ts.ToString(); // here we convert ts into String and Store in Temprary
// String variable.
DateTime TheTime = new DateTime(); // Creating the object of DateTime;
TheTime = Convert.ToDateTime(tIme); // now converting our temporary string into DateTime;
Console.WriteLine(TheTime.ToString(hh:mm:ss tt));
this will show the Result as: 02:00:00 PM
Normal Datetime can be converted in either 24 or 12 hours format.
For 24 hours format - MM/dd/yyyy HH:mm:ss tt
For 12 hours format - MM/dd/yyyy hh:mm:ss tt
There is a difference of captial and small H.
dateTimeValue.ToString(format, CultureInfo.InvariantCulture);

Categories