Convert 24 hour datetime to 12 hour format without using string - c#

I need to convert the datetime that is 24 hour format, and have to show it as 12 hour format. I got answers as , convert it into string as 12 hr format and show as string.
But I need to show as date time format. So i have used Convert.ToDateTime(datetime), but it again change datetime into 24 hour format , any better way to convert 12 hour format ?
Thanks in advance.

Following MSDN (DateTime Structure) :
Internally, all DateTime values are represented as the number of ticks (the number of 100-nanosecond intervals) that have elapsed since 12:00:00 midnight, January 1, 0001. The actual DateTime value is independent of the way in which that value appears when displayed in a user interface element or when written to a file. The appearance of a DateTime value is the result of a formatting operation. Formatting is the process of converting a value to its string representation.
So a DateTime is just a number of ticks.
If you want to display the date, then you actually want to format this number into a human readable format.

Here is an example:
Action<string> display = Console.WriteLine;
DateTime now = DateTime.Now;
display($"24 hour format: {now:F}"); // 13:31:20
display($"12 hour format: {now:hh:mm:ss}"); // 01:31:20
display($"24 hour format: {now:HH:mm:ss}"); // 13:31:20

Related

C# can a DateTime property on an entity have its day be today's day everyday automatically or does it need something like an update method?

I have a DateTime property for which I've only set the time:
OpenHour = DateTimeOffset.ParseExact("12:00:00 AM", "hh:mm:ss tt", CultureInfo.InvariantCulture)
But the day has also been saved as the day I've saved this property value.
I only wanted to set the time without the day so that it would be the same time every day.
Is there a way to do this ? Or do I need to create as CronJob to update every date's day to today's day ?
Edit
I'm not trying to create a time only value but know which way is best between creating a Cron Job to update the day of the time every day or if there's a better way.
And I tried to save it as strings but I needed to change it to DateTime to be able to use OrderBy when querying the place's list of hours and I've tried with strings it wasn't working.
Thank you for your help
It is not possible to save "just the time" as a DateTime object.
A DateTime object actually stores the current time as a single integer, and then when you see the result it is filtered through a certain timezone and format.
"The time component of a DateTimeOffset value is measured in 100-nanosecond units called ticks, and a particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. (C.E.) in the GregorianCalendar calendar. " *(source) https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset?view=net-5.0
If you want to avoid having to update it every day you could store it as a string representing the time and then have a method to automatically parse that time into todays date into a newly instantiated DateTime object.
string timeOfDay = DateTime.Now.ToString("hh:mm tt");
static DateTime TodayAtTime(string timeOfDay)
{
string calendarDay = DateTime.Now.ToString("MM/dd/yyyy ");
return DateTime.Parse(calendarDay + timeOfDay);
}
DateTime todayAtTime = TodayAtTime(timeOfDay);
Console.WriteLine(todayAtTime.ToString("hh:mm tt MM/dd/yyyy"));
Console.WriteLine(todayAtTime.ToString("dddd, dd MMMM yyyy HH:mm:ss"));

DateTime Format not working exactly C#

I want to have date in specific forma dd-mm-yyyy 15-05-2018 and my input date format on textbox is also dd-mm-yyyy in backend code c# i am converting this date into DateTime for input validation purpose.
DateTime dDateOfBirth;
if (!string.IsNullOrEmpty(txtDOB.Text))
{
dDateOfBirth= DateTime.ParseExact(txtDOB.Text, "dd-mm-yyyy",null);
}
When i check dDateOfBirth it stores shows me dates as 05/21/2018 while i want to pass it as 21-05-2018
Not sure what i am doing wrong
Using
DateTime.ParseExact(txtDOB.Text, "dd-MM-yyyy",null); also gives me same result MM/dd/yyyy
When you check the parameter dateOfBirth it will display in whatever is set as your machines culture. The date can be then formatted as a string, that you can customise.
Internally dates are handled as standardised objects, you can't change that. Effectively you are doing nothing wrong. It the same reason that if you were to inspect double dbl = 0.00 you would see dbl is "0" not "0.00.
If you wanted to set the text in the text box you would use:
txtDOB.Text = dDateOfBirth.ToString("dd-MM-yyyy").
For more info on formatting date time to strings see: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings and https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings
Also see: https://msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx
Especially
The DateTime value type represents dates and times with values ranging
from 00:00:00 (midnight), January 1, 0001 Anno Domini (Common Era)
through 11:59:59 P.M., December 31, 9999 A.D. (C.E.) in the Gregorian
calendar.
Time values are measured in 100-nanosecond units called ticks, and a
particular date is the number of ticks since 12:00 midnight, January
1, 0001 A.D. (C.E.) in the GregorianCalendar calendar (excluding ticks
that would be added by leap seconds). For example, a ticks value of
31241376000000000L represents the date, Friday, January 01, 0100
12:00:00 midnight. A DateTime value is always expressed in the context
of an explicit or default calendar.
So from this, you can take away that a date is just a really big number. When inspecting a date using breakpoints / watches etc, VisualStudio displays that as something more friendly for us mere humans.
In the dd-mm-yyyy format, mm should be MM. So try with MM.
Try This :
DateTime dateTime = new DateTime();
dateTime = Convert.ToDateTime(DateTime.ParseExact("YouDateString", "dd-MM-yyyy", CultureInfo.InvariantCulture));
I use following code to make it work in dd-MM-yyyy format, There may be other ways to do it i just wanted to it simple to one line of code.
if (!string.IsNullOrEmpty(txtDOB.Text))
{
dDateOfBirth= DateTime.ParseExact(txtDOB.Text, "dd-MM-yyyy",null);
//dDateOfBirth is in MM/dd/yyyy format
//so i am using next statement to convert to dd-MM-yyyy format
string sdDateOfBirth = dFromDate.ToString("dd-MM-yyyy");
}

Convert Human readable date into an epoch time stamp

I am working on a C# project where I have a date/time in the format of 2012-11-24 15:35:18 and I need to convert this into an epoch time stamp.
Everything I've found on Google is to convert an epoch time stamp into a human readable but I need it to be done the other way round.
Thanks for any help you can provide.
I found this here:
epoch = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
Instead of DateTime.Now, you should be able to input your desired time.
You didn't say your exact use case, but the standard .NET DateTime has a Ticks attribute which is defined as:
The value of this property represents the number of 100-nanosecond
intervals that have elapsed since 12:00:00 midnight, January 1, 0001,
which represents DateTime.MinValue. It does not include the number of
ticks that are attributable to leap seconds.
This is essentially an epoch based time, if it will suit your needs. Otherwise, with this value, you should be easily able to compute a conversion to another epoch time keeping method.
You need to use TryParse:
string input = "2012-11-24 15:35:18";
DateTime dateTime;
if (DateTime.TryParse(input, out dateTime))
{
ulong epoch = (dateTime.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
}

Convert Date to Milliseconds

I am working with Visual Studio 2010, MVC 3 and C#. I am creating some highcharts and need to have the x-axis be a date. I am pulling the dates from a database and adding them to and array that will then be passed to highcharts. I think highcharts requires the dates to be in millisecond format. Ho do I go about converting a DateTime of '12/20/2011 5:10:13 PM" for example to milliseconds?
Once you figure out what you want to calculate milliseconds from, you can just take one DateTime object from another to get a TimeSpan object. From TimeSpan you can get TotalMilliseconds.
In other words, if start and end are DateTime objects, you can do this:
double milliseconds = (end - start).TotalMilliseconds;
You can use the DateTime.Ticks property and convert the value to milliseconds.
The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds.
A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond.
The .Ticks in C# DateTime gives you the value of any time in ticks. You can thereafter convert to milliseconds as shown below:
long dateticks = DateTime.Now.Ticks;
long datemilliseconds = dateticks / TimeSpan.TicksPerMillisecond;
DateTime[] dates = ;
var minDate = dates.Min();
var msDates = dates.Select(date => (date - minDate).TotalMilliseconds).ToArray();

C# strange with DateTime

I got some strange result for:
Console.WriteLine(new DateTime(1296346155).ToString());
Result is:
01.01.0001 0:02:09
But it is not right!
I parsed value 1296346155 from some file. It said that it is in UTC;
Please explain;)
Thank you for help!)))
DateTime expects "A date and time expressed in the number of 100-nanosecond intervals that have elapsed since January 1, 0001 at 00:00:00.000 in the Gregorian calendar." (from msdn)
This question shows how you can convert a unix timestamp to a DateTime.
The constructor for DateTime that accept long type is expecting ticks value, not seconds or even milliseconds, and not from 1/1/1970 like in other languages.
So 1296346155 ticks is 129 seconds.
If it's Unix time, then the following should yield the expected result;
DateTime baseTime = new DateTime(1970, 1, 1, 0, 0, 0);
Console.WriteLine(baseTime.AddSeconds(1296346155));
See Unix Time for more information.
That constructor is not what you want as the time is not measured in ticks.
DateTime start = new DateTime(1970,1,1,0,0,0,0);
start = start.AddSeconds(1296346155).ToLocalTime();
Console.WriteLine(start);
// You don't need to use ToString() in a Console.WriteLine call
Ive found the following subject where there is a conversion between unix timestamp (the one you have) and .Net DateTime
How to convert a Unix timestamp to DateTime and vice versa?
That is correct - what were you expecting it to be and why?
The constructor System.DateTime(Int64) takes the number of 100-nanosecond intervals (known as Ticks) since January 1st 0001 (in the Gregorian calendar).
Therefore, 1296346155 / 10000000 gives you the number of seconds, which is 129.6.
Therefore, this should display 2 minutes and 9 seconds since midnight on 1st January 0001.

Categories