Jax
Jax

Reputation: 997

How to add current time in a datetime control if the time is not written

I have a GridView and SqlDataSource,

I have a column type: DateTime. If I type only the date in the TextBox, then the time will be 00:00:00. Is there any way of auto adding the current time if is not specified?

Thanks

Upvotes: 2

Views: 1199

Answers (2)

David East
David East

Reputation: 32604

When you type only the date in the TextBox you can still submit and add the current time onto the Date.

DateTime inputDate = // However you are gathering the date ;
DateTime dateWithCurrentTime = inputDate.Add(DateTime.Now.TimeOfDay);

DateTime has an Add function that allows you to add a TimeSpan to get a new DateTime object.

If you add the current time of day (DateTime.Now.TimeOfDay) to the input you gathered, you will get a new DateTime object with the current time of day and the date that was input.

Upvotes: 1

seN
seN

Reputation: 1095

Without any specific code, I can only answer your question vague but this might give you an Idea.

Serverside Solution: All in Code behind:

// To get the Time of right now 
DateTime oNow = DateTime.Today;

// Get your entered Time assuming it is Entered YYYY/MM/DD
string sEnteredDate = DateTextBox.Text;

// Edit the String to get Year, Month, Day
string sEnteredYear = sEnteredDate.Substring(0, 4);
string sEnteredMonth = sEnteredDate.Substring(5, 2);
string sEnteredDay = sEnteredDate.Substring(8, 2);

// Create final DateTime
DateTime oDateForDb = oNow;

oDateForDb.Day = sEnteredDay;
oDateForDb.Month = sEnteredMonth;
oDateForDb.Year = sEnteredYear;

Now oDateForDb should have the Date you want and the current hh:mm:ss.

Furthermore this whole concept should work just fine with Calender Extender or similar to guarantee that the Input is going to be the right DateFormat f.e. YYYY/MM/DD


EDIT:

Client Side Solution

http://www.tizag.com/javascriptT/javascriptdate.php

Do the same as Above only this time in jscript.

Upvotes: 1

Related Questions