DateTime Format not working exactly C# - 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");
}

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

Convert 24 hour datetime to 12 hour format without using string

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

Julian Time stamp to Date Time

I am trying to convert to Julian Time Stamp to Date Time. I have the following microseconds time stamp 212302469304212709. As i understand i need to add these milliseconds to the beginning of Julian Calendar (January 1, 4713 B.C., 12:00 (noon)). So i have the following method:
private DateTime GetDateTime(string julianTimeStamp)
{
var julianMilliseconds = Convert.ToDouble(julianTimeStamp)/1000;
var beginningOfTimes = new DateTime(1, 1, 1, 0, 0, 0, 0);
var dateTime = beginningOfTimes.AddMilliseconds(julianMilliseconds).AddYears(-4713).AddMonths(-1).AddDays(-1).AddHours(-12);
return dateTime;
}
Assume i pass 212302469304212709 string as the parameter. The expected result should be 2015/07(July)/01 00:08:24.212. Based on my method, i have almost the same result, but day is not 1, it is 6. Same problem for different time stamps i tested.
Could any one tell me what i am doing wrong? Thanks in advance.
Edited:
This is the exact date time i expect to receive: 2015(year) 7(month) 1(day) 0(hour) 8(minute) 24(second) 212(millisecond) 709(microsecond)
The given timestamp 212,302,469,304,212,709 μs when converted to days (just divide by 86,400,000,000) gives 2457204.505836 days (to six decimal places, which is the best I can do without a lot of extra trouble). Using the Multi Year Computer Interactive Almanac (MICA) written by the United States Naval Observatory, and putting in the free form date 2015(year) 7(month) 1(day) 0(hour) 8(minute) 24(second) 212(millisecond) 709(microsecond), the program calculates exactly the same day count (to six decimal places), proving the time stamp is an accurate Julian date.
One problem with the OP's calculation is trying to use the DateTime class before the earliest supported date, as pointed out by another poster. Also, the OP didn't say if 1 July 2015 was in the Julian or Gregorian calendar, but the MICA calculation proves it is in the Gregorian calendar. Since the OP is working in the Gregorian calendar, the epoch of Julian dates should be stated in the Gregorian proleptic calendar: Noon Universal Time, November 24, 4714 BC. The oft-quoted date January 1, 4713 BC is a proleptic Julian calendar date.
"Proleptic" means a date has been found by beginning at a modern date, who's calendar date is known with absolute certainty, and applying the rules of the chosen calendar backward until the desired date is reached, even though the desired date is before the chosen calendar was invented.
DateTime uses Gregorian calendar, so when you substract years, months and so on you are doing it with that calendar, not the Julian.
Unfortunately DateTime does not support dates before year 1. You can check the library in this post, maybe it helps you.

C# difference between two dates where one ends with a Z?

I have two dates
DateTime date1Z = DateTime.Parse("2014-05-22 23:39:29Z");
DateTime date1ZKind = DateTime.SpecifyKind(DateTime.Parse("2014-05-22 23:39:29Z"), DateTimeKind.Utc);
DateTime date2 = DateTime.Parse("2014-05-22 23:39:29");
DateTime date2Kind = DateTime.SpecifyKind(DateTime.Parse("2014-05-22 23:39:29"), DateTimeKind.Utc);
Console.WriteLine(date1Z);
Console.WriteLine(date1ZKind);
Console.WriteLine(date2);
Console.WriteLine(date2Kind);
Prints
23/05/2014 11:39:29 a.m.
23/05/2014 11:39:29 a.m.
22/05/2014 11:39:29 p.m.
22/05/2014 11:39:29 p.m.
Can someone explain whats going on here?
Using the suffix "Z" is date shorthand for saying that the Date-Time is "Zulu" time which is another word for UTC time. The first two dates are being parsed as UTC, while the last two are being parsed as whatever time is on the computer in question.
So to answer you question of what is going on: the latter two dates are being offset by your local time, which is apparently +12:00 (plus twelve hours), while the first two are not (as they are marked as "Zulu" or UTC time).
You live in New Zealand, which is +12 over UTC. That matches the date difference you are experiencing. As mentioned, the Z stands for UTC.

How can I convert a DateTime value to a double?

How do I convert a DateTime value to a double?
If, by double you mean an OLE Automation date, then you can use DateTime.ToOADate(). From the linked MSDN topic:
An OLE Automation date is implemented as a floating-point number whose value is the number of days from midnight, 30 December 1899. For example, midnight, 31 December 1899 is represented by 1.0; 6 A.M., 1 January 1900 is represented by 2.25; midnight, 29 December 1899 is represented by -1.0; and 6 A.M., 29 December 1899 is represented by -1.25.
The base OLE Automation Date is midnight, 30 December 1899. The maximum OLE Automation Date is the same as MaxValue, the last moment of 31 December 9999.
If you're talking about some other date representation that can also be stored in a double, please specify...
DateTime.ToOADate() converts to a double OLE Automation Date in C#
Yes, OLE Automation date enable Datetime to convert to Decimal/double type. However, the outcome/value to decimal/double is not exact system Datetime.
For example,
Decimal dateIndDec = Convert.Decimal (Datetim.Today.ToOADate());
is not equal to MS SQL
Select Convert (Decimal (10, 9), GetDate())
Conclusion: OLE Automation date is not a true system datetime info... cannot use it.
I've been searched everywhere about convert Datetime value to Decimal value in C# without any luck.
You can calculate difference between your DateTime and DateTime.MinValue, and then get any Total* value.
var difference = DateTime.Now - DateTime.MinValue;
Console.WriteLine(difference.TotalMinutes);
Console.WriteLine(difference.TotalMilliseconds);

Categories