I have a need to convert a string value in the form "YYYYMMDDHHMMSS" to a DateTime. But not sure on how, may be a DateTime.Tryparse can be used to make this happen. Or is there any other way to do it. I can do this using some string operations to take "YYYYMMDD" alone, convert to a datetime and then add HH, MM, SS separately to that DateTime. But is there any DateTime.TryParse() methods that I can use in one line to convert a "YYYYMMDDHHMMSS" format string value to a DateTime value?
Define your own parse format string to use.
string formatString = "yyyyMMddHHmmss";
string sample = "20100611221912";
DateTime dt = DateTime.ParseExact(sample,formatString,null);
In case you got a datetime having milliseconds, use the following formatString
string format = "yyyyMMddHHmmssfff"
string dateTime = "20140123205803252";
DateTime.ParseExact(dateTime ,format,CultureInfo.InvariantCulture);
Thanks
You have to use a custom parsing string. I also suggest to include the invariant culture to identify that this format does not relate to any culture. Plus, it will prevent a warning in some code analysis tools.
var date = DateTime.ParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
class Program
{
static void Main(string[] args)
{
int transactionDate = 20201010;
int? transactionTime = 210000;
var agreementDate = DateTime.Today;
var previousDate = agreementDate.AddDays(-1);
var agreementHour = 22;
var agreementMinute = 0;
var agreementSecond = 0;
var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);
DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));
Console.WriteLine("Selected Date : " + selectedDate.ToString());
Console.WriteLine("Start Date : " + startDate.ToString());
Console.WriteLine("End Date : " + endDate.ToString());
if (selectedDate > startDate && selectedDate <= endDate)
Console.WriteLine("Between two dates..");
else if (selectedDate <= startDate)
Console.WriteLine("Less than or equal to the start date!");
else if (selectedDate > endDate)
Console.WriteLine("Greater than end date!");
else
Console.WriteLine("Out of date ranges!");
}
}
Related
I see that this question has been answered for Java, JavaScript, and PHP, but not C#. So, how might one calculate the number of days between two dates in C#?
Assuming StartDate and EndDate are of type DateTime:
(EndDate - StartDate).TotalDays
The top answer is correct, however if you would like only WHOLE days as an int and are happy to forgo the time component of the date then consider:
(EndDate.Date - StartDate.Date).Days
Again assuming StartDate and EndDate are of type DateTime.
Use TimeSpan object which is the result of date substraction:
DateTime d1;
DateTime d2;
return (d1 - d2).TotalDays;
I think this will do what you want:
DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(-1);
TimeSpan t = d1 - d2;
double NrOfDays = t.TotalDays;
DateTime xmas = new DateTime(2009, 12, 25);
double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;
// Difference in days, hours, and minutes.
TimeSpan ts = EndDate - StartDate;
// Difference in days.
int differenceInDays = ts.Days; // This is in int
double differenceInDays= ts.TotalDays; // This is in double
// Difference in Hours.
int differenceInHours = ts.Hours; // This is in int
double differenceInHours= ts.TotalHours; // This is in double
// Difference in Minutes.
int differenceInMinutes = ts.Minutes; // This is in int
double differenceInMinutes= ts.TotalMinutes; // This is in double
You can also get the difference in seconds, milliseconds and ticks.
In case someone wants numer of whole days as a double (a, b of type DateTime):
(a.Date - b.Date).TotalDays
There often is a debate on time (hours) when it comes to counting days between two dates. The responses to the question and their comments show no exception.
Considering StartDate and EndDate are of type DateTime: if performance is not a concern, I would strongly recommend documenting your calculation through intermediate conversions. For example, (EndDate - StartDate).Days is unintuitive because rounding will depend on the hour component of StartDate and EndDate.
If you want the duration in days to include fractions of days, then as already suggested
use (EndDate - StartDate).TotalDays.
If you want the duration to reflect
the distance between two days, then use (EndDate.Date - StartDate.Date).Days
If you want the duration to reflect the
duration between the morning of the start date, and the evening of
the end date (what you typically see in project management software), then use
(EndDate.Date - StartDate.Date).Days + 1
You can try this
EndDate.Date.Subtract(DateTime.Now.Date).Days
Using a timespan would solve the problems as it has many attributes:
DateTime strt_date = DateTime.Now;
DateTime end_date = Convert.ToDateTime("10/1/2017 23:59:59");
//DateTime add_days = end_date.AddDays(1);
TimeSpan nod = (end_date - strt_date);
Console.WriteLine(strt_date + "" + end_date + "" + "" + nod.TotalHours + "");
Console.ReadKey();
For a and b as two DateTime types:
DateTime d = DateTime.Now;
DateTime c = DateTime.Now;
c = d.AddDays(145);
string cc;
Console.WriteLine(d);
Console.WriteLine(c);
var t = (c - d).Days;
Console.WriteLine(t);
cc = Console.ReadLine();
For beginners like me that will stumble upon this tiny problem, in a simple line, with sample conversion to int:
int totalDays = Convert.ToInt32((DateTime.UtcNow.Date - myDateTime.Date).TotalDays);
This calculates the total days from today (DateTime.UtcNow.Date) to a desired date (myDateTime.Date).
If myDateTime is yesterday, or older date than today, this will give a positive (+) integer result.
On the other side, if the myDateTime is tomorrow or on the future date, this will give a negative (-) integer result due to rules of addition.
Happy coding! ^_^
First declare a class that will return later:
public void date()
{
Datetime startdate;
Datetime enddate;
Timespan remaindate;
startdate = DateTime.Parse(txtstartdate.Text).Date;
enddate = DateTime.Parse(txtenddate.Text).Date;
remaindate = enddate - startdate;
if (remaindate != null)
{
lblmsg.Text = "you have left with " + remaindate.TotalDays + "days.";
}
else
{
lblmsg.Text = "correct your code again.";
}
}
protected void btncal_Click(object sender, EventArgs e)
{
date();
}
Use a button control to call the above class. Here is an example:
You can use the code below:
int DateDifInSecond = EndDate.Subtract(StartDate).TotalSeconds
Get the difference between the two dates and then get the days from:
int total_days = (EndDate - StartDate).TotalDays
try this truly worked Get actual days diff. date format is "dd/MM/yyyy"
string[] d1 = txtFromDate.Values.Split('/');
string[] d2 = txtToDate.Values.Split('/');
DateTime FrmDt = new DateTime(Convert.ToInt32(d1[2]), Convert.ToInt32(d1[1]), Convert.ToInt32(d1[0]));
DateTime ToDt = new DateTime(Convert.ToInt32(d2[2]), Convert.ToInt32(d2[1]), Convert.ToInt32(d2[0]));
TimeSpan TDiff = ToDt.Subtract(FrmDt);
String DaysDiff = TDiff.TotalDays.ToString();
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
DateTime d = Calendar1.SelectedDate;
// int a;
TextBox2.Text = d.ToShortDateString();
string s = Convert.ToDateTime(TextBox2.Text).ToShortDateString();
string s1 = Convert.ToDateTime(Label7.Text).ToShortDateString();
DateTime dt = Convert.ToDateTime(s).Date;
DateTime dt1 = Convert.ToDateTime(s1).Date;
if (dt <= dt1)
{
Response.Write("<script>alert(' Not a valid Date to extend warranty')</script>");
}
else
{
string diff = dt.Subtract(dt1).ToString();
Response.Write(diff);
Label18.Text = diff;
Session["diff"] = Label18.Text;
}
}
I am making a scheduling system using VS2012 and SQLSERVER2012
I already validated that if the desired schedule day and time is already taken it will not submit.
This is the code
string sqlString = "Select [Date],[StartTime],[EndTime] FROM tbl_Schedule where [Date] ='" + txtDate.Value.ToShortDateString() + "' AND [StartTime] = '"+txtStart.Text+"' AND [EndTime] = '"+txtEnd.Text+"' ;";
How can I determine if my desired scheduled time is 1hr before the existing scheduled time.
string desiredTime = "10/10/2017 09:18";
DateTime d = DateTime.Parse(desiredTime);
string existingTime = "10/10/2017 10:18";
DateTime e = DateTime.Parse(existingTime);
if ((e-d).Hours <= 1)
{
Console.WriteLine("true");
}
(Datetime e - DateTime d) will give you a TimeSpan object, then you just check the hours on that to see if it's less than or equal to 1.
string desiredTime = "10/10/2017 09:18";
DateTime d = DateTime.Parse(desiredTime);
string existingTime = "10/10/2017 10:18";
DateTime e = DateTime.Parse(existingTime);
if (e.Hour - d.Hour == 1)
{
Console.WriteLine("true");
}
I'm trying to calculate difference between two dates, my code is given below
DateTime daterenew = DateTime.Parse(drow.ItemArray.GetValue(16).ToString()); //18/01/2017
DateTime datecurrent = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy"));
renewstatuslbl.Text = ((daterenew - datecurrent).Days) + " Day(s) remains";
But I'm getting an error
"String was not recognized as a valid DateTime."
I would simplify that:
var daterenew = DateTime.ParseExact("18/01/2017", "dd/MM/yyyy", CultureInfo.InvariantCulture);
var res = ((daterenew - DateTime.Today).Days) + " Day(s) remains";
Note, that DateTime.Now != DateTime.Today.
Try something like this
string dateString = drow.ItemArray.GetValue(16).ToString();
DateTime daterenew = DateTime.ParseExact(dateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
renewstatuslbl.Text = string.Format("{0} Day(s) remains", (daterenew - DateTime.Now).TotalDays);
Idea is in ParseExact where you can set up format for your date in drow.ItemArray
Also look at TotalDays
Assuming your drow.ItemArray.GetValue(16).ToString()format is always dd/MM/yyyy. Use ParseExact
DateTime daterenew = DateTime.ParseExact(drow.ItemArray.GetValue(16).ToString(), "dd/MM/yyyy", null); //18/01/2017
//DateTime datecurrent = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy"));
DateTime datecurrent = DateTime.Now;
renewstatuslbl.Text = ((daterenew - datecurrent).Days) + " Day(s) remains";
The format of the date , causes the error. 18/01/2017
https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
example I used "yyyy/MM/dd"
//DateTime daterenew = DateTime.Parse("18/01/2017"); //18/01/2017
DateTime daterenew = DateTime.Parse("2017.01.18"); //18/01/2017
DateTime datecurrent = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy"));
object renewstatuslbl = ((daterenew - datecurrent).Days) + " Day(s) remains";
thus, I think you can change the string date format first of the value before inserting to drow.ItemArray
enter codenamespace FineCalculation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DateTime date01 = date1.Value;
DateTime date02 = date2.Value;
TimeSpan timeSpan = date02 - date01;
int days = Convert.ToInt16(timeSpan.TotalDays);
double fine = 0;
if(days < 30)
{
fine = days * 0.5;
}else if(days > 30 && days < 60)
{
fine = days * 0.5 * 0.75;
}else if(days > 60)
{
fine = days * 0.5 * 0.75 * 1;
}
MessageBox.Show("For "+ days + " days fine is " + fine.ToString());
}
}
} here
I have a function that can convert the standard date to persian standard date as you can see here:
public string ConvertToPersianToShow(DateTime datetime)
{
PersianCalendar persian_date = new PersianCalendar();
string date;
string year = Convert.ToString(persian_date.GetYear(datetime));
string Month = Convert.ToString(persian_date.GetMonth(datetime));
string day = Convert.ToString(persian_date.GetDayOfMonth(datetime));
date = year+"/" + Month + "/" + day;
return date;
}
But i have a problem with these outputs:
1394/5/1
1394/12/8
1395/7/12
These outputs should be like this :
1394/05/01
1394/12/08
1395/07/12
I can count the digit numbers of the day and month but i thing it isn't the best way to do that .could you please give me some help about how can i change these kind of outputs using stringformat?
All you need to do is add a leading zero. .ToString can be used.
string Month = persian_date.GetMonth(datetime).ToString("D2");
string day = persian_date.GetDayOfMonth(datetime).ToString("D2");
You can use this function:
private static string UpdateDate(string date)
{
date.PadLeft(2, '0');
}
date = year+"/" + UpdateDate(Month) + "/" + UpdateDate(day);
I have a data table, from Sage 100 ERP to be specific, that uses two separate columns to store the updated date and time (DateUpdated and TimeUpdated). I need to convert the data in these two fields to a DateTime object for comparisons. The dates look like "mm/dd/yyyy 12:00 AM" and the time is a decimal like 14.29297. So far I have been able to convert the time to the minute as follows:
private DateTime GetDateTime(string date, decimal time)
{
int hour = int.Parse(Math.Floor(time).ToString());
decimal minTemp = decimal.Parse((60 * (time - hour)).ToString());
int min = int.Parse(Math.Round(minTemp).ToString());
int sec = int.Parse(Math.Round(60 * (minTemp - min)).ToString());
string datetime = date + " " + hour.ToString() + ":" + min.ToString();
return DateTime.Parse(datetime);
}
I remove the 12:00AM from the date string before I pass it to this method. This works, but I'm loosing the seconds which is very important.
How can I convert the time to hours, minutes, and seconds?
It looks like you could avoid all that extra processing and just do this:
DateTime GetDateTime(string date, decimal time)
{
return DateTime.Parse(datetime).AddHours((double)time);
}
Just parse what you have:
private DateTime GetDateTime(string date, decimal time)
{
DateTime dt = DateTime.ParseExact(date, "MM/dd/yyyy hh:mm tt",
CultureInfo.InvariantCulutre);
double hours = Convert.ToDouble(time);
return dt.AddHours(hours);
}
Of course, it would be a lot easier if you had the correct data types to begin with. I have a feeling somewhere you have a DateTime and a double anyway (perhaps when you read the data from the database), and you are improperly converting them to string and decimal.
if it's not a typo - you are missing to append seconds value to the datetime string.
Replace This:
string datetime = date + " " + hour.ToString() + ":" + min.ToString();
With this:
string datetime = date + " " + hour.ToString() + ":" + min.ToString()+ ":" + sec.ToString();
Assuming your calculations are correct, did you try appending the second component to the datetime variable as follows:
string datetime = date + " " + hour.ToString() + ":" + min.ToString()
+ ":" + sec.ToString()
For the seconds try something like this:
int secTemp = int.Parse((Math.Round(60 * (minTemp - min))).ToString());
int sec = (secTemp<0?60 + secTemp:secTemp);
string datetime = date + " " + hour.ToString() + ":" + min.ToString()+ ":" + sec.ToString();
Hope it helps
Covert Decimal to Hour and Minute for single Database field
double convertData = 1.75
TimeSpan timespan = TimeSpan.FromHours(convertData);
string outputH = timespan.ToString("hh");
string outputM = timespan.ToString("mm");
Output will be 1 hour / 45 min