How to convert system.date.time to uk format

Hi Guys

I want to store syste.date.now within a datetime variable to compare dates but having problem specifying the layout for uk format.

So basically I have tired DateTime systemDate = Datetime.ParseExact(System.DateTime.now,“M/dd/yyyy”,system.Globalization.CultureInfo.InvariantCulture).ToString(“dd/MM/yyyy”).

But it is saying type mismatch as string cannot be used in datetime.

Any ideas how to resolve this issuse.

so you dont need to parse it as you are generating it from datetime.now

So just try Datetime.Now.Tostring(“dd/MM/yyyy”)

This will save it as a string

1 Like

That does work as a string. But I need it as a date time. So afterwards I have tried using DateTime.Parse(systemDate) - systemDate the string output of Datetime.Now.Tostring(“dd/MM/yyyy”) inot a date time. But it says it is not in the correct format for date time.

@bobby
You don’t store a DateTime in a specific format, it’s just a DateTime. It only changes when you output it in a specific format. Your UK date and my American date DateTime variables are identical, they only differ when we output them.

1 Like

Yeah but I want to compare the dates so they have to be in the same format. One date is uk format and the system.date.time.now outputs an american format date despite my system being uk based. So I have to change the format to comapre them.

@bobby
The dates do not need to be in the same format to compare them. As long as they’re both stored in DateTime variables you can compare them with <,>, and =.

Please see below. I save a UK format date and then store it in a DateTime variable. The right-hand side of the ukDate assign statement below is DateTime.ParseExact(ukString,"dd/MM/yyyy",CultureInfo.InvariantCulture). Then I compare it to today. In this case the code outputs “Dates are the same.” since the If statement is true.

image

1 Like

Wow you are correct. It worked with just using DateTime.today. But what if the system date was US and the Uk date was being used. How does it convert accordling.

@bobby
If you’re parsing a string then the computer will convert however you tell it to convert. If it’s just accessing system time it doesn’t need to convert it. DateTimes are stored internally as a number of ticks (1 tick = 100 nanoseconds) since the beginning of year 1. No matter the format of the date the number of ticks remains the same.

1 Like

Thank you man. I did not know that.

2 Likes

I’m glad I could help! Dates and times are definitely one of the more convoluted aspects of programming since there are so many different ways that various cultures display that information.

2 Likes

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.