How do I convert to DateTime when the time is a decimal? - c#

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

Related

how to format string to hh:mm:ss?

I am trying to make a digital clock in C#. I have 3 counter objects for hours, minutes and seconds. It has to be in format hh:mm:ss.
What I managed to do
String hours = _hours.Value.ToString();
String minutes = _minutes.Value.ToString();
String seconds = _seconds.Value.ToString();
if (hours.Length == 1)
{
hours = "0" + hours;
}
if (minutes.Length == 1)
{
minutes = "0" + minutes;
}
if (seconds.Length == 1)
{
seconds = "0" + seconds;
}
return hours + ":" + minutes + ":" + seconds;
It works but I am trying for a more efficient way of doing it using String.format. I have tried few different regular expressions but have been unsuccessful.
string b = string.Format("{0:D2}:{1:00}:{2:d2}", hours, minutes, seconds);
Cheers
Have you tried converting the string into int, before trying your string.Format? Something like below
string.Format("{0:00}:{1:00}:{2:00}",
int.Parse(hours), int.Parse(minutes), int.Parse(seconds));
If _hours.Value, _minutes.Value and _seconds.Value are numeric types, then you can use the below code which is more efficient
string.Format("{0:00}:{1:00}:{2:00}",
_hours.Value, _minutes.Value, _seconds.Value);
You can always try something a bit different:
DateTime dt = new DateTime(2000, 1, 1, hours, minutes, seconds); // just ignore year, month and day
var x = dt.ToString("HH:mm:ss");
IMO if you already have a string type it's useless to cast it to int or DateTime just to stringify it again after that.
I would use String.PadLeft method :
string h = hours.PadLeft(2, '0');
string m = minutes.PadLeft(2, '0');
string s = seconds.PadLeft(2, '0');
string result = h + ":" + m + ":" + s;
PadLeft will make your string to always have length at least of the value passed as a first parameter ( 2 in this case ) and fill "empty" places with the value passed in second parameter ( 0 in this case ).
Check this online
You can use the formatting options available on the ToString() method of DateTime like below:
(new DateTime(1900, 1, 1, _hours.Value, _minutes.Value, _seconds.Value)).ToString("HH:mm:ss");
You can try using:
string b = DateTime.Now.ToString("HH:mm:ss");
If you have some date variable, you can do so:
string b = dateVar.ToString("HH:mm:ss");
If you want solution exactly for your example, then:
return string.Format("{0:00}:{1:00}:{2:00}",
int.Parse(hours),
int.Parse(minutes),
int.Parse(seconds)
);

calculate difference between two dates using c#

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

convert standard date to standard persian date in c#

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

Calculate time different between PM and AM in c# windows phone 7

I am trying to calculate time difference in PM and AM.
I have data of Monday 1:01 PM and tuesday 1:00AM.
I used below code to calculate the time difference.
And the result i get is:
-12 hour and -1 minutes
How should i go about doing it getting the correct time difference?
Below is the code:
if ((dayNow == "Monday") && (tues == "True"))
{
DateTime timeNow = DateTime.ParseExact(DateTime.Now.ToShortTimeString(),
"h:mm tt", new DateTimeFormatInfo());
DateTime timeSelected = DateTime.ParseExact(timePicker.ValueString,
"h:mm tt", new DateTimeFormatInfo());
TimeSpan timeLeft = timeSelected.Subtract(timeNow);
if (timeSelected > timeNow)
{
string hour = timeLeft.Hours.ToString();
string minute = timeLeft.Minutes.ToString();
string timeDifference = "This alarm is set for " + "1 day and "
+ hour + " hour and " + minute + " minutes from now.";
MessageBox.Show(timeDifference, "Alarm", MessageBoxButton.OK);
NavigationService.Navigate(new Uri("/listOfAlarm.xaml?",
UriKind.Relative));
}
else if (timeSelected < timeNow)
{
string hour = timeLeft.Hours.ToString();
string minute = timeLeft.Minutes.ToString();
string timeDifference = "This alarm is set for " + hour +
" hour and " + minute + " minutes from now.";
MessageBox.Show(timeDifference, "Alarm", MessageBoxButton.OK);
NavigationService.Navigate(new Uri("/listOfAlarm.xaml?",
UriKind.Relative));
}
else
{
NavigationService.Navigate(new Uri("/listOfAlarm.xaml?",
UriKind.Relative));
}
}
Bit Late to the show, but here is what I did.
An If statement, that figures out whether the time you have selected is greater than, or less than. If it is less than, then it will automatically add 24 hours to compensate, thus removing the negative sign and compensating for the program.
I converted the times to Integers, and then did this:
if (timeSelected > timeNow)
{
int_hour = Convert.ToInt16(hour); // Convert the string to integer
}
else
{
int_hour = Convert.ToInt16(hour) + 24; // Convert the string to integer ( Compensates for Negative)
}
Does replacing:
TimeSpan timeLeft = timeSelected.Subtract(timeNow);
with
TimeSpan timeLeft = timeNow.Substract(timeSelected);
fix your problem?

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

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!");
}
}

Categories

Resources