Using DateTime With input from a textbox.text - c#

I have this code that when executed gives me 74 Days, which is correct, but the date for oldDate has to come from a TextBox. Does anyone know how to do this as the DateTime only takes three integers.
private void myButton_Click(object sender, RoutedEventArgs e)
{
string myDate = myTextBox.Text;
DateTime oldDate = new DateTime(2013, 6, 5);
DateTime newDate = DateTime.Now;
// Difference in days, hours, and minutes.
TimeSpan ts = oldDate - newDate;
// Difference in days.
int differenceInDays = ts.Days;
differenceInDays = ts.Days;
myTextBlock.Text = differenceInDays.ToString();
}

You can parse the date from the user:
string myDate = myTextBox.Text;
DateTime oldDate;
if (!DateTime.TryParse(myDate, out oldDate))
{
// User entered invalid date - handle this
}
// oldDate is set now
That being said, depending on the UI framework, a more appropriate control (ie: the DateTimePicker from the extended WPF toolkit, etc) may be easier to use.

From your code you have to obtain oldDate from myTextBox, which you have stored in myDate string variable. You can convert it to datetime
oldDate=Convert.ToDateTime(myDate);
But since it might cause exception use following
`DateTime myyDateTime;if(DateTime.TryParse(myDate, out myDateTime){//use your date difference code here}

Related

How to convert the "time" from DateTime into int?

I have a DataGrid which contains a few values that are in hours and I wanted to know:
How to get ONLY the time from my DataGrid and convert it into an int (or double) variable.
My goal is to do a few operations with my DataGrid time values, like to add numbers into it
EXAMPLE:
Using my "dataGridView1.Rows[1].Cells[2].Value.ToString();" It'll show a DateTime value (which is inside my DataGrid), with this value, I wanna filter ONLY the time from this and convert it into an int
the part of my code which I wanna "capture" the time:
txtAtiv.Text = dataGridView1.Rows[0].Cells[1].Value.ToString();
string value = dataGridView1.Rows[0].Cells[2].Value.ToString();
lblLeft.Text = value.Split(' ')[1];
I wanna get the "value" (which is a DateTime value from the DataGrid) and convert it into an int.
note:
- The date for me in my dataGrid it's not relevant, I only have to pick the time (and yes, I know that I can't "split" DateTime to do them separately)
If you are willing to be limited to millisecond resolution, then this is fairly easy.
Given a date/time that you want to get the time part from as an int, you can get the number of milliseconds since midnight, like so:
DateTime dateTime = DateTime.Now;
int timeMsSinceMidnight = (int)dateTime.TimeOfDay.TotalMilliseconds;
If you want to reconstitute the original date and time from this, you need the original date and the time since midnight in milliseconds:
DateTime date = dateTime.Date; // Midnight.
DateTime restoredTime = date.AddMilliseconds(timeMsSinceMidnight);
Test program:
DateTime dateTime = DateTime.Now;
Console.WriteLine("Original date/time: " + dateTime );
int timeMsSinceMidnight = (int)dateTime.TimeOfDay.TotalMilliseconds;
DateTime date = dateTime.Date; // Midnight.
DateTime restoredTime = date.AddMilliseconds(timeMsSinceMidnight);
Console.WriteLine("Restored date/time: " + restoredTime);
The value returned from time.TimeOfDay is of type TimeSpan, which is convenient for storing time-of-day values.
If you want to turn your "milliseconds since midnight" back into a TimeSpan, you just do this:
var timeSpan = TimeSpan.FromMilliseconds(timeMsSinceMidnight);
First step is to convert string to DateTime. Use DateTime.TryParse(string value, out DateTime dt). Then as Mathew Watson rightly suggested, get the value of variable dt converted to milliseconds using dt.TimeOfDay.TotalMilliseconds. It is also possible to convert the span in TotalSeconds or TotalMinutes if it suits your requirement.
Try to avoid calling ToString() method directly before checking if cell value is null. If I want to avoid the check, I would make compiler to do it by using something like : Rows[3].Cells[2].Value + "" instead of Value.ToString().
Mixing Mathew's and Mukesh Adhvaryu's answers, I got into this one, and it fits perfectly on what I need, thank you guys for your support!
txtAtiv.Text = dataGridView1.Rows[0].Cells[1].Value + "";
string value = dataGridView1.Rows[0].Cells[2].Value + "";
lblLeft.Text = value.Split(' ')[1];
textStatus.Text = "";
DateTime timeConvert;
DateTime.TryParse(value, out timeConvert);
double time;
time = timeConvert.TimeOfDay.TotalMilliseconds;
var timeSpan = TimeSpan.FromMilliseconds(time);
lblSoma.Text = timeSpan.ToString();
static void Main(string[] args)
{
string time1 = "11:15 AM";
string time2 = "11:15 PM";
var t1 = ConvertTimeToInt(time1);
var t2 = ConvertTimeToInt(time2);
Console.WriteLine("{0}", t1);
Console.WriteLine("{0}", t2);
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", ConvertIntToTime(t1));
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", ConvertIntToTime(t2));
Console.ReadLine();
}
static long ConvertTimeToInt(string input)
{
var date = DateTime.ParseExact(input, "hh:mm tt", CultureInfo.InvariantCulture);
TimeSpan span = date.TimeOfDay;
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", date);
return span.Ticks;
}
static DateTime ConvertIntToTime(long input)
{
TimeSpan span = TimeSpan.FromTicks(input);
var date = new DateTime(span.Ticks);
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", date);
return date;
}

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 change "ddd" datetime format to a number view

I want to make that code to show me a current datetime on my pc clock when i click a button... i did it with that code listed down. But here is my question how can i make the "ddd" (day of a week) to be shown in number, not in words, I mean:
00-sunday
01-monday
and etc. ...
This is my code for the button:
private void SetClock_Click(object sender, EventArgs e)
{
SetClock.Click += new EventHandler(SetClock_Click);
{
DateTime time = DateTime.Now;
string format = "yy-MM-dd-ddd-hh-mm-ss";
txtSend.Text = time.ToString(format);
}
}
What i have to add to make it. Thanks
txtSend.Text = string.Format("{0:yy-MM-dd}-{1:00}-{0:hh-mm-ss}", time, (int)time.DayOfWeek);
A format isn't required, you can just cast DayOfWeek to an int:
var dayAsInt = (int)DateTime.Now.DayOfWeek;
Looking at the Custom Date and Time Format Strings page, there doesn't appear to be a format string for it :-(
The following should do it:
txtSend.Text =
time.ToString("yy-MM-dd-") +
((int)time.DayOfWeek).ToString("00") +
time.ToString("-hh-mm-ss");
You could use this to get the day of week numeric
int dayofweek = (int)DateTime.Now.DayOfWeek;

To get time along with Date from DateTimePicker

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);

How can I convert ticks to a date format?

I am converting a ticks value to a date like this:
Convert(datetime, (MachineGroups.TimeAdded - 599266080000000000)/864000000000);
Using this i get:
9/27/2009 10:50:27 PM
But I want just the date in this format:
October 1, 2009
My sample ticks value is
633896886277130000
What is the best way to do this?
A DateTime object can be constructed with a specific value of ticks. Once you have determined the ticks value, you can do the following:
DateTime myDate = new DateTime(numberOfTicks);
String test = myDate.ToString("MMMM dd, yyyy");
It's much simpler to do this:
DateTime dt = new DateTime(633896886277130000);
Which gives
dt.ToString() ==> "9/27/2009 10:50:27 PM"
You can format this any way you want by using dt.ToString(MyFormat). Refer to this reference for format strings. "MMMM dd, yyyy" works for what you specified in the question.
Not sure where you get October 1.
private void button1_Click(object sender, EventArgs e)
{
long myTicks = 633896886277130000;
DateTime dtime = new DateTime(myTicks);
MessageBox.Show(dtime.ToString("MMMM d, yyyy"));
}
Gives
September 27, 2009
Is that what you need?
I don't see how that format is necessarily easy to work with in SQL queries, though.
Answers so far helped me come up with mine. I'm wary of UTC vs local time; ticks should always be UTC IMO.
public class Time
{
public static void Timestamps()
{
OutputTimestamp();
Thread.Sleep(1000);
OutputTimestamp();
}
private static void OutputTimestamp()
{
var timestamp = DateTime.UtcNow.Ticks;
var localTicks = DateTime.Now.Ticks;
var localTime = new DateTime(timestamp, DateTimeKind.Utc).ToLocalTime();
Console.Out.WriteLine("Timestamp = {0}. Local ticks = {1}. Local time = {2}.", timestamp, localTicks, localTime);
}
}
Output:
Timestamp = 636988286338754530. Local ticks = 636988034338754530. Local time = 2019-07-15 4:03:53 PM.
Timestamp = 636988286348878736. Local ticks = 636988034348878736. Local time = 2019-07-15 4:03:54 PM.

Categories