To get time along with Date from DateTimePicker - c#

I have a datetimepicker whose format is short.I have to get time along with date in code behind.Now 12:00:00 am is inserting along with date.Instead i need to insert current time along with date picked from datetimepicker.Can anybody help?

Create a new DateTime using the date from your input and the time from DateTime.Now.
DateTime GetDateAndCurrentTime(DateTime date)
{
return new DateTime(date.Year, date.Month, date.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
}

The actual DateTime.Value from the picker is a full DateTime object with the current time.
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
DateTime dt = dateTimePicker1.Value;
// or
string s = string.Concat(dt.ToShortDateString(), DateTime.Now.ToShortTimeString());
}

Full DateTime:
dateTimePicker1.Value;
'08/21/2011 14:42:11'
Short DateTime:
dateTimePicker1.Value.Date;
'08/21/2011 00:00:00'
The minimum value
'08/21/2011 00:00:00'
The maximum value
'08/21/2011 23:59:59'
Usage:
var firstDate = dtpFrom.Value.Date; // 0:00:00
var secondDate = dtpTo.Value.Date.AddSeconds(86400 - 1); //23:59:59 - 86400 is 24 hours
var list = Services.GetListForFilter(firstDate, secondDate);

Related

String to Date with current Time

I want to convert date entered int String to DateTime type
I use the following
DateTime date = Convert.ToDateTime(dateText);
Let say the dateText=5/20/2014 DateTime date become 5/20/2014 and 12:00:00 AM. I I want the current time of the day to be picked up instead of 12:00:00 AM.
Is there a workaround?
After you do:
DateTime date = Convert.ToDateTime(dateText);
Then do:
DateTime fullDate = new DateTime(date.Year, date.Month, date.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
...or as suggested by Ulugbek Umirov:
DateTime fullDate = date.Add(DateTime.Now.TimeOfDay);
Try this :
DateTime date = Convert.ToDateTime(dateText + " " + DateTime.Now.TimeOfDay);

add Seconds to a date and get new date

How to Get new Date provided a date and number of seconds passed from that date.For Example 03-12-2014 12:30:02 AM is the date and 124 are the seconds lapsed then new date time should be 03-12-2014 12:32:06 AM
Try something like:
string strDate = "03-12-2014 12:30:02 AM ";
DateTime date;
if (DateTime.TryParse(strDate , out date))
{
date = date.AddSeconds(124);
}
Use addition operator with a TimeSpan:
var date = myDate + TimeSpan.FromSeconds(124);

Date difference returning wrong answer

I would really like some guidance on this problem i have been facing.
I am trying to find out the difference between 2 dates from textbox.
protected void Button1_Click(object sender, EventArgs e)
{
a = TextBox1.Text.ToString().Trim();
b = TextBox2.Text.ToString().Trim();
DateTime c = new DateTime();
DateTime d = new DateTime();
c = Convert.ToDateTime(a);
d = Convert.ToDateTime(b);
System.TimeSpan diffr = d - c;
Response.Write(diffr.Days);
}
The above is the code i have written on Button Click event.
The problem is that, the code returns the difference wrong.
i.e if the diff between 12/02/2013 and 11/02/2013 is to be found, instead of returning 1
the code returns 30.
Similarly diff between 12/02/2013 and 10/02/2013 is to be found, instead of returning 2
the code returns 61.
I am using the Jquery DatePicker for selecting the date!
Kindly help as all my search has not yielded any solutions.
You should convert your date format to dd/mm/yyyy before doing substraction.
So here is your final code-
protected void Button1_Click(object sender, EventArgs e)
{
string a, b;
a = TextBox1.Text.ToString().Trim();
b = TextBox2.Text.ToString().Trim();
DateTime c = new DateTime();
DateTime d = new DateTime();
c = Convert.ToDateTime(a);
d = Convert.ToDateTime(b);
DateTime to_datetime = DateTime.ParseExact(a, "dd/MM/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
DateTime from_datetime = DateTime.ParseExact(b, "dd/MM/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
System.TimeSpan diffr = to_datetime - from_datetime;
Response.Write(diffr.Days);
}
The only problem is the format of the date.
As you have written it is showing the month difference rather than date difference.
Try using datetime.parseexact and specify your format
Example:-
string poop = "2005-12-14T14:35:32.1700000-07:00";
DateTime poo = DateTime.ParseExact(poop,"yyyy-MM-ddTHH:mm:ss.fffffffzzz",
System.Globalization.CultureInfo.InvariantCulture);
In your case
string sDate1=TextBox1.Text.ToString().Trim();
string sDate2=TextBox1.Text.ToString().Trim();
DateTime dt1= DateTime.ParseExact(sDate1,"MM-dd-yyyy",
System.Globalization.CultureInfo.InvariantCulture);
DateTime dt2= DateTime.ParseExact(sDate2,"MM-dd-yyyy",
System.Globalization.CultureInfo.InvariantCulture);
System.TimeSpan diffr =dt2 - dt1;
Response.Write(diffr.Days);
And it should work.
You can change the jQuery datepicker's date format as
$("#txtDate.datepicker").datepicker({ dateFormat: 'mm-dd-yy' });
In jQuery, you can parse the test to date as
var dateInJs = $.datepicker.parseDate('mm-dd-yy', $('#txtDate.datepicker').val());
Or in .NET you can parse the date in 'dd-MM-yyyy' format as
DateTime.ParseExact(txtDate.Text, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
also you can use CultureInfo in .NET like
DateTime Date = DateTime.Parse(txtDate.Text, System.Globalization.CultureInfo.CreateSpecificCulture("hi-IN"));
Perhaps you can use TimeSpan:
DateTime startTime = '';
DateTime endTime = '';
TimeSpan span = endTime.Subtract( startTime );
Next you can utilize span.Seconds, span.Days...etc
I think this problem is due to your computer date time format setting. Please change your computer date time format to dd/MM/yyyy format and try again.

How to set time to midnight for current day?

Every time that I create a non-nullable datetime in my mvc3 application it defaults to now(), where now is current date with current time. I would like to default it to today's date with 12am as the time.
I'm trying to default the time in my mvc...but...the following isn't setting to todays date #12am. Instead it defaults to now with current date and time.
private DateTime _Begin = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 12, 0, 0);
public DateTime Begin { get { return _Begin; } set { _Begin = value; } }
How can I set to 12am for the current date for non-nullable datetime?
You can use the Date property of the DateTime object - eg
DateTime midnight = DateTime.Now.Date;
So your code example becomes
private DateTime _Begin = DateTime.Now.Date;
public DateTime Begin { get { return _Begin; } set { _Begin = value; } }
PS. going back to your original code setting the hours to 12 will give you time of noon for the current day, so instead you could have used 0...
var now = DateTime.Now;
new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
I believe you are looking for DateTime.Today. The documentation states:
An object that is set to today's date, with the time component set to 00:00:00.
http://msdn.microsoft.com/en-us/library/system.datetime.today.aspx
Your code would be
DateTime _Begin = DateTime.Today;
Using some of the above recommendations, the following function and code is working for search a date range:
Set date with the time component set to 00:00:00
public static DateTime GetDateZeroTime(DateTime date)
{
return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
}
Usage
var modifieddatebegin = Tools.Utilities.GetDateZeroTime(form.modifieddatebegin);
var modifieddateend = Tools.Utilities.GetDateZeroTime(form.modifieddateend.AddDays(1));
Only need to set it to
DateTime.Now.Date
Console.WriteLine(DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss"));
Console.Read();
It shows
"2017-04-08 00:00:00"
on my machine.
Related, so I thought I would post for others. If you want to find the UTC of the start of today (for your timezone) the following code works for any UTC offset (-23.5 thru +23.5). This looks like we add X hours then subtract X hours, but the important thing is the ".Date" after the add.
double utcOffset= 10.0; // Set to your UTC offset in hours (eg. Melbourne Australia)
var now = DateTime.UtcNow;
var startOfToday = now.AddHours(utcOffset - 24.0).Date;
startOfToday = startOfToday.AddHours(24.0 - utcOffset);
Most of the suggested solutions can cause a 1 day error depending on the time associated with each date. If you are looking for an integer number of calendar days between to dates, regardless of the time associated with each date, I have found that this works well:
return (dateOne.Value.Date - dateTwo.Value.Date).Days;
Try this:
DateTime Date = DateTime.Now.AddHours(-DateTime.Now.Hour).AddMinutes(-DateTime.Now.Minute)
.AddSeconds(-DateTime.Now.Second);
Output will be like:
07/29/2015 00:00:00

How to get differences of dates

I am making a web page in that I have used Ajax calendar to pick two date like TO date and From date and I also have a Textbox of total days.
So when user selects to and from dates, the difference of these dates is displayed in the textbox. So how can I find the difference of these dates..?
I set the format like dd/MM/yyyy.
e.g.
one textbox has: 20/04/2012
second has : 02/05/2012
So, please find difference on these ?
Thanks in Advance....
Mitesh
Substraction operator (-) works on DateTime
DateTime to_datetime = DateTime.ParseExact(to_textbox.Text, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
DateTime from_datetime = DateTime.ParseExact(from_textbox.Text, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
Timespan result = to_datetime - from_datetime;
You can use it as
textBox1.Text = (to_datetime - from_datetime).TotalDays.ToString();
Convert your textbox values to date using:
DateTime dt1 = DateTime.ParseExact(textbox1.Text, "d/M/yyyy", CultureInfo.InvariantCulture);
DateTime dt2 = DateTime.ParseExact(textbox2.Text, "d/M/yyyy", CultureInfo.InvariantCulture);
Use TimeSpane
TimeSpan ts = dt1.Subtract(dt2);
Console.Write(ts.TotalDays);
textBox3.Text = ts.TotalDays;
Assuming C# code: DateTime support "-" that results in TimeSpan object.
DateTime nowTime = DateTime.Now;
DateTime yesterday = nowTime.AddDay(-1);
TimeSpan diff = nowTime - yesterday;
DateTime date1 =DateTime.ParseExact("20/04/2012","d/M/yyyy",null);
DateTime date2 = DateTime.ParseExact("02/05/2012", "d/M/yyyy", null);
TimeSpan datediff = date2 - date1;
Response.Write(datediff.ToString());

Categories