0

I am relatively new to C# and any suggestions to the query below i will greatly appreciate.

I've gone through a lot of articles here but none of the solutions seems to work in my case

Im reading DATETIME from sql and passing it to a string

dateStart = rd1["DATE_START"].ToString();

when debugging in VS it's showing date time in a format i like: 22/11/2015 17:12:45 But Label is showing 11/22/2015 5:12:45 PM

When i use the code to ParseExact

dtime = DateTime.ParseExact(dateStart, "yyyy/MM/dd HH:mm:ss", provider);

No matter what i use for the format i always get

[FormatException: String was not recognized as a valid DateTime.]

DateTime dtime;
CultureInfo provider = CultureInfo.InvariantCulture;
provider = new CultureInfo("en-GB");
dateStart = rd1["DATE_START"].ToString();
dtime = DateTime.ParseExact(dateStart, "yyyy/MM/dd HH:mm:ss", provider);
LBDateOpened.Text = dtime.ToString();

I'm lost, please help.

4
  • Did you try not specifying the culture ? Commented Nov 24, 2015 at 20:50
  • 6
    Are you sure your query isn't returning an actual DATETIME type? If that were the case, you could just (DateTime)rd1["DATE_START"], which is significantly better than parsing it yourself. Commented Nov 24, 2015 at 20:50
  • The format string in ParseExact doesn't look, well, exact to the source string. Commented Nov 24, 2015 at 20:54
  • Thank you @CoryNelson. Your suggestion worked! dtime= (DateTime)rd1["DATE_START"]; LBDateOpened.Text = dtime.ToString("yyyy/mm/dd HH:mm:ss"); Commented Nov 24, 2015 at 20:58

1 Answer 1

2

Following should work fine...

var dateStart = (DateTime)rd1["DATE_START"]; // assign DateTime
var dateString = dateStart.ToString("yyyy/MM/dd HH:mm:ss"); // format to string
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.