views:

40

answers:

3

Hi I'm wanting to set a variable date in the format Y-m-d 20:00:00 of the previous day. can someone help?

A: 

Try

Dim lastEvening as DateTime = DateTime.Today.AddDays(-1).AddHours(20)

Formatted as asked

Dim formattedLastEvening as string = lastEvening.ToString("y-M-d HH:mm:ss")
Binary Worrier
A couple of nitpicks: *(1)* Using `AddDays(-1).AddHours(20)` will give incorrect results when it crosses a DST boundary, which usually occur in the early hours of the morning; *(2)* The `Y-M-D` section of the format string is invalid, it should probably be `y-M-d`.
LukeH
@Luke: You are of course correct sir, and have changed it to `y-M-d`.
Binary Worrier
+3  A: 
Dim lastNight As DateTime = DateTime.Today.AddHours(-4)

Dim lastNightString As String = lastNight.ToString("y-M-d HH:mm:ss")
LukeH
+1: Indeed, far more elegant than `.AddDays(-1).AddHours(20)`. Nice one.
Binary Worrier
A: 

There's probably an easier way but this is how I would probably do it in C#:

DateTime myDate = DateTime.Today.AddHours(20 - DateTime.Today.Hour).AddMinutes(0 - DateTime.Today.Minute).AddSeconds(0 - DateTime.Today.Second).AddMilliseconds(0 - DateTime.Today.Millisecond);

Then for formatting find something along the lines of: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx