why is datetime not recording time when stored? - c#

When recording a TimeStamp into the the table in the DB why does...
DateTime todaysDate = DateTime.Today;
BookingRecord newBooking = new BookingRecord();
//other code for adding record to db
newBooking.TimeStamp = todaysDate;
why does the record in timeStamp record as : 2013-09-04 00:00:00.000
I want the correct time to display as well?
thanks for reply

Because DateTime.Today is actually supposed to do that. Use DateTime.Now if you want the time information as well.
Edit: of course, it's recommended to use UTC DateTimes for storage in the database anyway, so it's probably best to use DateTime.UtcNow!

DateTime.Today will actually be today's date with the time portion set to 00:00:00:
http://msdn.microsoft.com/en-us/library/system.datetime.today.aspx
An object that is set to today's date, with the time component set to
00:00:00.

DateTime todaysDate = DateTime.Today;
change to
DateTime todaysDate = DateTime.Now;

Related

Retrieve Record from Database based on Local Time

Let's suppose I live in a timezone where Today Date is: 12/3/2014
Before saving record I save the date in UTC, so it would be 12/2/2014
user.Created = DateTime.UtcNow;
Now I have a Search page on which I would like to retrieve record based on the filter "Today". Also I would like to truncate time so I am using DbFunction of EF.
DateTime dateDifference = DateTime.Now.Date;
var result= queryableData
.Where(s => dateDifference ==
DbFunctions.CreateDateTime(s.Created.Year, s.Created.Month,
s.Created.Day, 0, 0, 0)).AsQueryable();
The above query does not return any record because the stored date is in UTC which 12/2/2014, however I am living in a timezone where date is 12/3/2014. So it make sense, how can I modify the above query to meet my requirement. Any suggestion
Now that we know that the value is stored as a DateTime (in UTC), you just need to find the UTC time of midnight at the start of today, and the UTC time of midnight at the end of today.
If you're happy to use the system time zone, you could use:
DateTime today = DateTime.Today;
DateTime startUtc = today.ToUniversalTime();
DateTime endUtc = today.AddDays(1).ToUniversalTime();
var result = queryableDate.Where(s => startUtc <= s.Created &&
s.Created < endUtc);
I don't think you should need DbFunctions for that query. Basically, you don't need a difference at all - you just need to work out what your filter of "today" means in terms of an interval in time, expressed as UTC.
Convert your local date to universal time.
DateTime universalDate = dateDifference.ToUniversalTime();

DateTime returns wrong date

I'm trying to get today's date
DateTime todayDateTime = new DateTime();
and I'm getting this:
{1/1/0001 12:00:00 AM}.
Why is this happening?
Use this
DateTime date = DateTime.Now;
Using new DateTime() creates a DateTime with a time of "0".
If you want todays date you need to use DateTime.Today if you want a DateTime object with a date of today and a time of 12:00:00 AM or DateTime.Now if you want a DateTime with the day and time of the moment you called DateTime.Now.
According to MSDN, the constructor for DateTime which takes in a long initializes by using the specified number of ticks since January 1st, 0001, so saying new DateTime(0) yields this time, not the current time.
Instead, use the static field DateTime.Now to get a DateTime representing the current system time.
In your question you are just initializing the Variable todayDateTime but you have never assigned (set it). This is why it is date ("null")/ beginning of our time calculations.
To actually get todays Date, you can use the following:
DateTime today = DateTime.Today;
first of all you need to assigned a value in the datetime.
just use something like this :
DateTime today = DateTime.Today;

store minutes to database

hello i'm new to programming i have the following problem
string tt = drpPickuptime.SelectedItem.Text;
DateTime mora = Convert.ToDateTime(tt);
I have also tried this
string tt = drpPickuptime.SelectedItem.Text;
DateTime mora = DateTime.Parse(tt, new CultureInfo("fr-FR")).Date;
and this 1 also
DateTime mora = DateTime.ParseExact(drpPickuptime.SelectedItem.Text, "mm", CultureInfo.CurrentCulture);
but the error is nor rectified. The problem is that i have a combobox and i have put just minuts there which will be selected by user. I want to store that value in database. But in database the data type of that field is datetime. When i change that to string the problem is solved. But isn't it possible to store that string in database with required conditions. Though it is not a good question but i have done my all effort on it and could;nt get the result. Can anyone help me please
The problem is that you cannot create a valid DateTime with just minutes, there needs to be a date (year, month, day).
If you are just storing minutes in the database then I would recommend an int type. If you really must have a DateTime then you will need to store a date too, perhaps Today's date is an option? in which case you can do this:
int minutes = int.Parse(drpPickuptime.SelectedItem.Text);
DateTime dt = DateTime.Today.AddMinutes(minutes);
I think the best would be to change the datatype to bigint, and store it as a timespan. You can store the Ticks property of the timespan in the database, then when you bring it back you just do TimeSpan.FromTicks(database field). And to store it you can do TimeSpan.FromMinutes(your comobobox value), you will have to parse the combobox value to an integer.
You can't store minutes as a DateTime in the database, as #Jon mentioned. You'd have to store the value as an integer. Then if you want to apply those minutes to some date value, you could do:
DateTime d = DateTime.Now.AddMinutes(tt);
or if you want those minutes in the past you could do:
DateTime d = DateTime.Now.AddMinutes(tt * -1);
You could also store it in the database as a string. Then in your code you can do an int.Parse to convert it from a string to an integer.

How to get DateTime with a UTC datetime and a particular timezone?

My data in SQL database looks like this:
PubDateUTC PubDateUTCOffset
----------------------- --------------------
2011-08-04 10:02:50.000 +8:00:00
2012-04-23 02:32:25.287 +8:00:00
2010-09-26 04:23:00.000 +8:00:00
What I want is to get a DateTime based on PubDateUTC and PubDateUTCOffset, for example:
2011-08-04 10:02:50.000, +8:00:00 should result in 2011-08-04 18:02:50:000
I have tried with TimeZoneInfo class, but I don't know hot to create a instance of TimeZoneInfo with a string like "+8:00:00", which would be the CreateTimeZoneInfo method below
var tz = CreateTimeZoneInfo(post.PubDateUTCOffset);
return TimeZoneInfo.ConvertTimeFromUtc(post.PubDateUTC, tz);
Is there anyway to do this?
Note: I cannot change the data in SQL database.
You could try something like:
var date = post.PubDateUTC.Add(
TimeSpan.Parse(post.PubDateUTCOffset.Replace("+", ""))
);
The .Replace("+", "") is because TimeSpan will handle -01:00:00 but will choke on +01:00:00
I think you need to use DateTimeOffset class. This thread may be helpful.
http://msdn.microsoft.com/en-us/library/bb546101.aspx
This works, remove any leading "+" from the offset ( "-" are ok)
var d = new DateTimeOffset(DateTime.Parse("2011-08-04 10:02:50.000"),
TimeSpan.Parse("08:00:00"));
d.DateTime - the time in db = 10:02:50
d.LocalDateTime - the time according to your servers timezone
d.UtcDateTime - the time at GMT = 02:02:50
I'm not sure you want 18:02:50 since it is the time at GMT+16 (+16:00:00), unless of course that is how it's encoded in the db, then just ignore this post :)
You should change your post class to have one property:
public DateTimeOffset Published { get; set; }
Then when you read from the database (assuming you have datetime and varchar types in your database):
DateTime utc = DateTime.SpecifyKind(
(DateTime) reader["PubDateUTC"], DateTimeKind.Utc);
TimeSpan offset = TimeSpan.Parse(
((string) reader["PubDateUTCOffset"]).Replace("+", ""))
post.Published = new DateTimeOffset(utc).ToOffset(offset);
Then when you need to consume it, you have all of the options of a full DateTimeOffset:
DateTime local = post.Published.DateTime; // with your offset applied
DateTime utc = post.Published.UtcDateTime; // the original utc value
string s = post.Published.ToString("o"); // 2011-08-04T18:02:50.0000000+08:00

How can I setup DateTime hour,minute and second?

private void StartAuction()
{
DateTime closeDate;
closeDate = DateTime.Parse(Console.ReadLine());
}
I am able to set the date,month and year but I want the hours,minutes and seconds to setup automatically to the current time of the day. for example if the current time is 15:24, I want the user to add the date which could be 21/03/2013 and then I want the time to be 15:24:00 and not 00:00:00 as it currently does.
Any suggestions?
Well you can use DateTime.Now to get the current time, then take the TimeOfDay from that and add it to the Date of your existing DateTime:
private void StartAuction()
{
DateTime closeDate = DateTime.Parse(Console.ReadLine());
DateTime closeDateAtCurrentTime = closeDate.Date + DateTime.Now.TimeOfDay;
...
}
(I'm explicitly using the Date property so that even if the user does enter a time as well, it's basically stripped.)
As a blatant plug, you might also want to consider using my Noda Time library, which separates out the ideas of "date", "time" and "date/time" into different types. (As well as "local" values vs ones where you know the UTC offset or the time zone.)
var now = DateTime.Now;
var date = new DateTime(input.Year, input.Month, input.Day, now.Hour, now.Minute, now.Second);
First you need to parse with DateTime.Parse what you read from command line.
Then, you can do that using DateTime.Now.TimeOfDay like;
DateTime closeDate = DateTime.Parse(Console.ReadLine());
closeDate = closeDate.Date + DateTime.Now.TimeOfDay;
You could do
closeDate = DateTime.Parse(Console.ReadLine() + " " + DateTime.Now.TimeOfDay);
Which works, but does look a little roundabout and I wouldn't recommend it considering you're converting from a time format to a string and then back to a time format again. Lots of immutable objects being created, there.
There are other options, including to parse the date, as you do, and then add TimeOfDay to it.
DateTime closeDate;
closeDate = DateTime.Parse(Console.ReadLine());
closeDate = closeDate.Date + Date.Now.TimeOfDay;
You can do this:
closeDate = DateTime.Parse(Console.ReadLine())
.Add(DateTime.Now - DateTime.Today);
Well how about this little function:
public static DateTime ChangeTime(DateTime dateTime)
{
return new DateTime(
dateTime.Year,
dateTime.Month,
dateTime.Day,
DateTime.Now.Hour,
DateTime.Now.Minute,
DateTime.Now.Second,
DateTime.Now.Millisecond,
DateTime.Now.Kind);
}
This is a possible solution:
store DateTime.Now in a variable
var date = DateTime.Now;
Then u can access the Hours, Minutes and Seconds like this:
date.Hour;
date.Minute;
date.Second;

Categories