-1

I tried to insert into my MS Access database a specific format to see how just the "time" in my database behaves, but when I tried to show what I got the date also, but I want to insert just the time.

I tried to convert the datetime variable to specific format and insert that

DateTime starttime = Convert.ToDateTime(DateTime.Now.ToShortTimeString());
DateTime nstarttime = Convert.ToDateTime(starttime.ToString("HH:mm"));

06/04/2019 22:55:00 that what I got and I want just the time without the date

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
crank
  • 11
  • 2

2 Answers2

1

Your main issue is, that in .Net the time part of a DateTime is not a DateTime but a TimeSpan:

DateTime dateTime = new DateTime(2019, 6, 4, 22, 55, 0);
TimeSpan timePart = dateTime.TimeOfDay;

In Access (VBA) however, a "time only" value is the time of the date of the VBA Date epoch which is 1899-12-30. Depending on how you insert the time in an Access table, you may have to apply the time part to the epoch to obtain a value like that Access would use:

DateTime dateTime = new DateTime(2019, 6, 4, 22, 55, 0);
TimeSpan timePart = dateTime.TimeOfDay;    
DateTime vbaEpoch = new DateTime(1899, 12, 30);
DateTime vbaTime = vbaEpoch.AddTicks(timePart.Ticks);

Of course, when reading back the values, ignore the date part:

TimeSpan timeOfDay = vbaTime.TimeOfDay;    
Gustav
  • 53,498
  • 7
  • 29
  • 55
0

This has been answered so many times, but nevertheless here is the link to one of the discussions Link 1:

Please check also this Link 2 with may useful patterns

This detail is one of the actual examples provided on Link 1:

DateTime dt = DateTime.Parse("6/22/2009 07:00:00 AM");
dt.ToString("HH:mm"); // 07:00 // 24 hour clock // hour is always 2 digits
dt.ToString("hh:mm tt"); // 07:00 AM // 12 hour clock // hour is always 2 digits
dt.ToString("H:mm"); // 7:00 // 24 hour clock
dt.ToString("h:mm tt"); // 7:00 AM // 12 hour clock

Hope this helps! Cheers and happy coding!

DasSoftware
  • 964
  • 10
  • 19