How can I convert decimal? to string? - c#

I'm writing an ASP.NET MVC program in C# and I have a date fetched from my database, but the date is set as a decimal type, and I can't change that. I need to know how I can format the decimal to look like 04/15/2017 instead of 20170415.00
This is how that column is declared in my model.
public decimal? SIM2_DUE_DATE { get; set; }
I'm calling the date from the database. I have over 1000 dates that need to be formatted. I just used that one as an example, so I can't format it specifically.

You can use math to convert your "date" to DateTime type. First spilt it into parts like this:
var date = 20170415.00M;
var year = (int)date / 10000;
var month = (int) date / 100 % 100;
var day = (int)date % 100;
then call a DateTime constructor:
var dateTime = new DateTime(year, month, day);

You could do this by using DateTime.ParseExact:
string dueDate = SIM2_DUE_DATE.ToString("D"); // remove decimals
var parsedDate = DateTime.ParseExact(dueDate, "yyyyMMdd", CultureInfo.InvariantCulture); // parse the date and ensure it's in that specific format
var display = parsedDate.ToShortDateString(); // get the culture-specific date representation
Notice that this would fail if you kept the decimals

Decimal decimalDateValue = 20170105.00;
DateTime dateEquivalent = DateTime.MinValue;
DateTime.TryParse(decimalDateValue.ToString(),out dateEquivalent);

Considering your date in decimal value
decimal dtdec = 20170415.00M;
You have few options
var newDate = DateTime.ParseExact(((Int64)dtdec).ToString(),
"yyyyMMdd",
System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(newDate.ToShortDateString());
Or
Console.WriteLine(DateTime.Parse(dtdec.ToString("####/##/##")));
Or
Console.WriteLine(dtdec.ToString("####/##/##"));

Related

How can I convert an German date format with two digits in year to UTC-format?

My Problem: I want to convert an german date "24.05.05" to the UTC-Format "2005-05-24". In German date format "24.05.05" the last two digits is the year 2005.
Here is my code which not works:
var lGermanDate = "24.05.05";
DateTime lOutDateTime;
CultureInfo lCultureInfo = new CultureInfo("de-de");
// expecting result to fail
if (DateTime.TryParseExact(lGermanDate, lCultureInfo.DateTimeFormat.ShortDatePattern, lCultureInfo, DateTimeStyles.None, out lOutDateTime))
{
var lTargetDate = lOutDateTime.ToString("yyyy-m-d");
}
else
{
[...]
}
Note: in PHP this works with the following code:
\DateTime::createFromFormat('d.m.y', $lGermanDate )->format('Y-m-d');
Have you try the following?
//To Convert lGermanDate into DateTime
string DATEPATTERN = "dd.MM.yy";
DateTime.TryParseExact(lGermanDate, DATEPATTERN, null, DateTimeStyles.None, out DateTime outGermanDate);
//From outGermanDate to UTC Format
string dateUTC = outGermanDate.ToString("yyyy-MM-dd")
Your parsing is fine, maybe a little too specific
m is minutes is DateTime.ToString() patterns, M is month
var germanDateStr = "24.05.05";
if (DateTime.TryParse(germanDateStr, out DateTime outDateTime))
{
var targetDate = outDateTime.ToString("yyyy-M-d");
targetDate.Dump();
}
else
{
}

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

Convert time string to DateTime in c#

How can I get a DateTime based on a string
e.g:
if I have mytime = "14:00"
How can I get a DateTime object with current date as the date, unless current time already 14:00:01, then the date should be the next day.
This is as simple as parsing a DateTime with an exact format.
Achievable with
var dateStr = "14:00";
var dateTime = DateTime.ParseExact(dateStr, "H:mm", null, System.Globalization.DateTimeStyles.None);
The DateTime.ParseExact() (msdn link) method simply allows you to pass the format string you wish as your parse string to return the DateTime struct. Now the Date porition of this string will be defaulted to todays date when no date part is provided.
To answer the second part
How can I get a DateTime object with current date as the date, unless
current time already 14:00:01, then the date should be the next day.
This is also simple, as we know that the DateTime.ParseExact will return todays date (as we havevnt supplied a date part) we can compare our Parsed date to DateTime.Now. If DateTime.Now is greater than our parsed date we add 1 day to our parsed date.
var dateStr = "14:00";
var now = DateTime.Now;
var dateTime = DateTime.ParseExact(dateStr, "H:mm", null, System.Globalization.DateTimeStyles.None);
if (now > dateTime)
dateTime = dateTime.AddDays(1);
You can use DateTime.TryParse(): which will convert the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.
string inTime="14:00";
if(DateTime.TryParse(inTime,out DateTime dTime))
{
Console.WriteLine($"DateTime : {dTime.ToString("dd-MM-yyyy HH:mm:SS")}");
}
Working example here
There is a datetime constructor for
public DateTime(
int year,
int month,
int day,
int hour,
int minute,
int second
)
So then parse the string to find the hours, minutes, and seconds and feed that into this constructor with the other parameters supplied by Datetime.Now.Day and so on.
I think you want to do something like this:
string myTime = "14:00";
var v = myTime.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
DateTime obj = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, int.Parse(v[0]), int.Parse(v[1]), DateTime.Now.Second);

Difference Between Dates Issue

I am having an issue of getting the difference in days between two dates. I will post my code below, but what I am trying to achieve is very simple, just get the difference between 2 dates in days and place the difference in a label.
Code:
string date1 = "";
string date2 = "";
if (myRdr.HasRows)
{
myRdr.Read();
date1 = myRdr["Date 1"].ToString();
date2 = myRdr["Date 2"].ToString();
}
Date 1 and Date 2 are what I am selecting from a query for SQL Server. The date format that I am pulling from my table is 12/25/2015
I have tried these lines to convert the string to date, but it returns nothing:
DateTime date1Diff= DateTime.ParseExact(date1, "dd/MM/yyyy", null);
DateTime date2Diff= DateTime.ParseExact(date2, "dd/MM/yyyy", null);
Then I was planning on getting the difference between date2Diff - date1Diff
So my question is, why are date1Diff and date2Diff returning nothing and what is the best way to get the difference between those two dates?
Put this method in class form or in the same form pass the string date format that you read it gives you date difference
public static double GetDateDiff(string d1, string d2)
{
double result = 0.0;
DateTime MyDate1 = Convert.ToDateTime(d1);
DateTime MyDate2 = Convert.ToDateTime(d2);
result = ((MyDate1 - MyDate2).TotalDays);
return result;
}

How to convert a date of integers to a formated date string (i.e. 2012009 to 2/01/2009)

Any ideas?
I can't come up with any.
I have a list of dates I'm loading in from a csv file and they are saved as all integers, or rather a string of integers (i.e. Jan 1, 2009 = 1012009)
Any ideas on how to turn 1012009 into 1/01/2009?
Thanks!
Since the date is stored as a string, you may want to use ParseExact:
DateTime date = DateTime.ParseExact("28012009", "dMMyyyy", null);
ParseExact will throw an exception if the format doesn't match. It has other overloads, where you can specify more than a single possible format, if that is required. Note that here provider is null, which uses the current culture.
Depending on style you may wish to use TryParseExact.
int date = 1012009;
var month = date / 1000000;
var day = (date / 10000) % 100;
var year = date % 10000;
var formatted = new DateTime(year, month, day).ToString();
This assumes month-day-year; if the numbers are day-month-year, I’m sure you’ll be able to swap the month and day variables to accommodate that.
If you want to customise the date format, you can do so as described in:
Standard Date and Time Format Strings
Custom Date and Time Format Strings
Let 10102009 be dateInt.
string dateString = dateInt.ToString();
int l = dateString.Length;
dateString = dateString.Insert(l-3,"/");
dateString = dateString.Insert(l-6,"/");
You should now have 1/01/2009 in dateString.. You can also try the ParseExact function..

Categories