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);
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 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
I am trying to convert Julian date string to DateTime but none of the solutions on the web seem to be working. I have a Julian date string 13324.
Julian Date: 13324
And I want to get the following DateTime
Date: 20-Nov-2013
Could you please direct me in the right direction. Thanks.
This is the simplest solution I can think of:
string julianDate = "13324";
int jDate = Convert.ToInt32(julianDate);
int day = jDate % 1000;
int year = (jDate - day) / 1000;
var date1 = new DateTime(year, 1, 1);
var result = date1.AddDays(day - 1);
(Note: this is all from memory; verify the syntax, etc.)
Sorry for my bad english
Try this code if the one on top didn't work. It worked for me.
public DateTime ConvertJulianToDatetime(string julianDate)
{
int dateint = int.Parse(julianDate);
DateTime dinicio = new DateTime(1840, 12, 31);
dinicio = dinicio.AddDays((double)dateint);
return dinicio;
}
This code is more reliable I think (can anyone notice):
public static DateTime FromJD(double JD)
{
return DateTime.FromOADate(JD - 2415018.5);
}
For MJD (modified julian day). Math.Floor or Math.Ceiling can be added as needed:
public static DateTime FromMJD(double MJD)
{
return DateTime.FromOADate((MJD - 2415018.5) + 2400000.5);
}
And one example for reverse translation:
public static double ToMJD(DateTime date)
{
return (date.ToOADate() + 2415018.5) -2400000.5;
}
public static double ToJD(DateTime date)
{
return date.ToOADate() + 2415018.5;
}
I have stored date of birth var char format:
Example: 1989-8-15
I want to find out sub string from it i.e I want separate year, month and date. I have tried it with following code:
string dateOfbirth = (string)(DataBinder.Eval(e.Item.DataItem, "dob"));
int length = (dateOfbirth).Length;
int index1 = dateOfbirth.IndexOf('-');
int index2 = dateOfbirth.IndexOf('-', index1 + 1);
string year = dateOfbirth.Substring(0, index1);
string month = dateOfbirth.Substring(index+1, index2-1);
string day = dateOfbirth.Substring(index2, length);
I am getting an error. Please suggest a solution. Thanks in advance.
You can try this
string [] date = dateOfbirth.Split('-');
string year = date[0];
string month = date[1];
string day = date[2];
DateTime dob = DateTime.ParseExact("1989-8-15","yyyy-M-dd",null);
Console.WriteLine(dob.Year);
Console.WriteLine(dob.Month);
Console.WriteLine(dob.Day);
Clean and easy.
UPD: changed Parse to ParseExact with a custom date format
I hope this will help:
string st= "1989-8-15"; /
string st = (string)(DataBinder.Eval(e.Item.DataItem, "dob"));
string [] stArr = st.Split('-');
So, you now have an array with dob items.
To actually answer your question:
string dateOfbirth = "1989-8-15";
int length = (dateOfbirth).Length;
int index1 = dateOfbirth.IndexOf('-');
int index2 = dateOfbirth.IndexOf('-', index1 + 1);
string year = dateOfbirth.Substring(0, index1);
string month = dateOfbirth.Substring(index1 + 1, index2 - index1 - 1);
string day = dateOfbirth.Substring(index2 + 1, length - index2 - 1);
It's just a matter of providing the correct parameters to the Substring method.
Using dateOfBirth.Split('-') would probably be at better solution for your problem, though.
Use TryParseExact to avoid exception due to different culture settings
DateTime dateValue;
var dateString="1989-08-15";
if(DateTime.TryParseExact(dateString, "yyyy-MM-dd", CultureInfo.InvariantCulture,DateTimeStyles.None, out dateValue))
{
// parse successfull
Console.WriteLine(dateValue.Year);
Console.WriteLine(dateValue.Month);
Console.WriteLine(dateValue.Day);
}
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!");
}
}