Link to home
Start Free TrialLog in
Avatar of websss
websssFlag for Kenya

asked on

converto datetime always changes format

Hi

I wish to have a datatime object stored as yyyy-MM-dd
everytime i convert to a string it works

everytime i convert back to date time it always changes format to dd-MM-yyyy
see here:
User generated image
how to i store as datetime object while preserving formatting
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

You can't as a datetime.  A DateTime is the raw information.  How it is formatted is up to you afterwards.
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If you stored the string representation then you preserve to display but you lose the ability to manipulate, sort and filter on the date easily.
a date time is stored as a number which is the # of seconds past the epoch date.  How it is displayed is up to you.
DateTime:23/01/2017 2:48:23 PM
Double:42758.6169402546
Long:636207797036385320
 static void Main(string[] args)
        {
            DateTime sDate;
                sDate = DateTime.Now;

            double ddate;
            long ldate;
            Console.WriteLine("DateTime:" + sDate);
            ddate = sDate.ToOADate();
            Console.WriteLine("Double:" + ddate);
            ldate = sDate.Ticks;

            Console.WriteLine("Long:" + ldate);
            Console.ReadKey();

        }

Open in new window

Avatar of websss

ASKER

i'm actually trying to save these to DB in yyyy-MM-dd hh:mm:ss
however, i can only do this when converting to string, as soon i i convert back to datetime, it goes back to other format

the DB field is datetime, so i need to pass in a datetime and not a string
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
As I said in the first comment.  No.  A datetime is just the raw value without any formatting, you choose how to display it when it is required.  So if you always require yyyy-MM-dd hh:mm:ss then choose that as the display format
as you refer to database, please also read this article to understand the concept of date/time conversions at that level:
https://www.experts-exchange.com/articles/1499/DATE-and-TIME-don't-be-scared-and-do-it-right-the-first-time.html