Adding two dates to eachother - c#

string final = Convert.ToString(DateTime.Parse(date, System.Globalization.CultureInfo.InvariantCulture) + TimeSpan.Parse(duration));
Hi, I use the above code to add two date's to eachother. It do work very well on Windows and returns the required format yyyy-MM-dd HH:mm:ss in a correct fashion. HOWEVER, when on Linux building with Mono it returns the following format dd/MM/yyyy HH:mm:ss which is not what I want.
How can I specify that I ONLY want the first formatting and nothing else? I tried playing around with ParseExact but it did not do very well. What I've heard ParseExact should not really be needed for this?
Here is a example of input:
string date = "2014-10-30 10:00:04"; // On windows
string duration = "05:02:10"; // duration to be added to date
Greetings.

Use ToString("yyyy-MM-dd HH:mm:ss") instead of Convert.ToString.
string date = "2014-10-30 10:00:04";
string duration = "05:02:10";
DateTime dt1 = DateTime.Parse(date, CultureInfo.InvariantCulture);
TimeSpan ts = TimeSpan.Parse(duration, CultureInfo.InvariantCulture);
DateTime dtFinal = dt1.Add(ts);
string final = dtFinal.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
Convert.ToString uses your current culture's date separator, use CultureInfo.InvariantCulture.
Read: Custom Date and Time Format Strings

You can use the ToString() Method of the DateTime object.
var dt = DateTime.Now;
dt.ToString("yyyy-MM-dd HH:mm");

Using your code:
string _final = (DateTime.Parse(date, System.Globalization.CultureInfo.InvariantCulture) + TimeSpan.Parse(duration)).ToString("yyyy-MM-dd HH:mm:ss");

Related

Format DateTime object from System time format to required format

My system time is of the format dd-MMM-yy (02-Dec-16). The format I want to convert it to is "yyyy/MM/dd". I've basically been playing around with all the other datetime formats that my system offers and this is the parsing statement I've figured out that works for All of them (except this) -
CultureInfo provider = CultureInfo.InvariantCulture;
string date_format = "yyyy/MM/dd HH:mm:ss tt";
DateTime now_value = DateTime.ParseExact(DateTime.Now.ToString(date_format), date_format, provider);
return now_value.ToString(date_format);
But this doesn't work for the aforementioned dd-MMM-yy format. Can someone please tell me what I am doing wrong here?
(Sidebar -Is there a more efficient way in which I can write this above snippet?)
You don't need to convert DateTime to string and then convert back to DateTime and again back to string, if you have DateTime input just call the ToString with the format as below
string dt =DateTime.Now.ToString("yyyy/MMM/dd", CultureInfo.InvariantCulture);
for your example :
DateTime now_value = DateTime.ParseExact("02-Dec-16", "dd-MMM-yy", System.Globalization.CultureInfo.InvariantCulture);
return now_value.ToString("yyyy/MM/dd");
Try This:
string date_format = "yyyy-MMM-dd";
string date_now = DateTime.Now.ToString(date_format,CultureInfo.CreateSpecificCulture("en-US"));
return date_now;
Even This should also work:
string date_format = "yyyy-MMM-dd";
string date_now = DateTime.Now.ToString(date_format);
return date_now;
I think best way would be to create an extension method for multiple date formats,
var inputDate = "02-Dec-2016";
string[] availaible_input_date_format = { "dd-MMM-yyyy", "dd/MMM/yyyy" }; // add as many formats availible
var date_format = "yyyy/MMM/dd";
DateTime outputDate;
DateTime.TryParseExact(inputDate, availaible_input_date_format, null, DateTimeStyles.None, out outputDate);
Console.WriteLine(outputDate.ToString(date_format));
You can try this:
datetime yourdatetime = new datetime();
string converteddatetime = yourdatetime.toString("yyyy/MM/dd");

DateTime.Parse Not Parsing

I'm trying to return the date as "2015-06-18"
string strDate = DateTime.Now.ToString("yyyy-MM-dd");
DateTime newDate = DateTime.Parse(strDate);
This returns "2015/06/18 hh:mm:ss"
What am I missing?
If you want a particular output format, you can specify one yourself.
string strDate = DateTime.Now.ToString("yyyy-MM-dd");
DateTime newDate = DateTime.Parse(strDate);
string output = newDate.ToString("yyyy-MM-dd");
Console.WriteLine (output); // produces 2015-06-18 right now
The DateTime structure in .net always includes the time of day, and there is no built-in way to store only a date, so if you want to exclude it, you'll need to use the formatting options.
What you need is to format the datetime object.
newDate.ToString("yyyy-MM-dd") -> 2015-06-19
Why don't you just use the DateTime.Date property?
DateTime date1 = DateTime.Now;
Console.WriteLine(date1.ToString());
// Get date-only portion of date, without its time.
DateTime dateOnly = date1.Date;
// Display date using short date string.
Console.WriteLine(dateOnly.ToString("yyyy-MM-dd"));

DateTime string format in c#

I have a project that contain 3 string variables.
DateFormatStr is the format string I need to use to output dates.
DateFormatFrom is the start date a request will apply from
FilloutDateTo is the end date the request will apply to.
The problem is that I don't want to manually specify the dates. As you can see in my example below (a working example), I need to specify the dates, but is there a way to make it that the from date has time 00:00:00 and the end date has time 23:59:59?
string DateFormatStr = "MM/dd/yy hh:mm:ss tt";
string DateFormatFrom = "12/04/14 00:00:00";
string FilloutDateTo = "12/04/14 23:59:59";
So I would like to the system time to recognize the from date and the start date respecting the formatStr variable.
Thanks
If I understand correctly, you can use DateTime.Today property like;
var dt1 = DateTime.Today;
var dt2 = DateTime.Today.AddDays(1).AddSeconds(-1);
and use DateTime.ToString() to format them like;
var DateFormatFrom = dt1.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
var FilloutDateTo = dt2.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Results will be;
12/04/2014 00:00:00
12/04/2014 23:59:59
You used hh format specifier but it is for 12-hour clock. Use HH format specifier instead which is for 24-hour clock. And since your result strings doesn't have any AM/PM designator, you don't need to use tt format specifier.
In C# 6.0 you can use string interpolation in order to display formatted dates.
DateTime startOfDay = DateTime.Today;
DateTime endOfDay = DateTime.Today.AddDays(1).AddTicks(-1);
string dateFormatFrom = $"{startOfDay: MM/dd/yy hh:mm:ss tt}";
string filloutDateTo = $"{endOfDay: MM/dd/yy hh:mm:ss tt}";
string idate = "01/11/2019 19:00:00";
DateTime odate = Convert.ToDateTime(idate);
DateTime sdate1 = DateTime.Parse(idate);
string outDate1 = String.Format("{0}/{1}/{2}", sdate1.Day, sdate1.Month,sdate1.Year);
Console.WriteLine(outDate1);

Converting System Date Format to Date Format Acceptable to DateTime in C#

How can I convert a system date format (like 3/18/2014) to the format readable in DateTime?
I wanted to get the total days from two dates, which will come from two TextBoxes.
I have tried this syntax:
DateTime tempDateBorrowed = DateTime.Parse(txtDateBorrowed.Text);
DateTime tempReturnDate = DateTime.Parse(txtReturnDate.Text);
TimeSpan span = DateTime.Today - tempDateBorrowed;
rf.txtDaysBorrowed.Text = span.ToString();
But tempDateBorrowed always returns the minimum date for a DateTime varibale. I think this is because DateTime does not properly parse my system date format. As a consequence, it incorrectly displays the number of days. For example, if I try to enter 3/17/2014 and 3/18/2014 respectively, I always get -365241 days instead of 1.
Edit: I wanted my locale to be non-specific so I did not set a specific locale for my date format. (My system format by the way is en-US)
Try DateTime.ParseExact method instead.
See following sample code (I've used strings instead of TextBoxes since I used a Console app to write this code). Hope this helps.
class Program
{
static void Main(string[] args)
{
string txtDateBorrowed = "3/17/2014";
string txtReturnDate = "3/18/2014";
string txtDaysBorrowed = string.Empty;
DateTime tempDateBorrowed = DateTime.ParseExact(txtDateBorrowed, "M/d/yyyy", null);
DateTime tempReturnDate = DateTime.ParseExact(txtReturnDate, "M/d/yyyy", null);
TimeSpan span = DateTime.Today - tempDateBorrowed;
txtDaysBorrowed = span.ToString();
}
}
ToString is not Days
TimeSpan.TotalDays Property
You can try specifying the format of the datetime in the textboxes like this
DateTime tempDateBorrowed = DateTime.ParseExact(txtDateBorrowed.Text.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
DateTime tempReturnDate = DateTime.ParseExact(txtReturnDate.Text.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
Also you may have to check if the values from the textboxes are valid.
My first thought is to just replace the TextBox controls with a DateTimePicker or equivalent, depending on what platform you're developing on. Converting strings to dates or vice-versa is more of a pain than it seems at first.
Or you could try using DateTime.ParseExact instead, to specify the exact expected format:
DateTime tempDateBorrowed =
DateTime.ParseExact("3/17/2014", "M/dd/yyyy", CultureInfo.InvariantCulture);
Or you could specify a specific culture in the call to DateTime.Parse:
var tempDateBorrowed = DateTime.Parse("17/3/2014", new CultureInfo("en-gb"));
var tempDateBorrowed = DateTime.Parse("3/17/2014", new CultureInfo("en-us"));
try formatting your date to iso 8601 or something like that before parsing it with DateTime.Parse.
2014-03-17T00:00:00 should work with DateTime.Parse. ("yyyy-MM-ddTHH:mm:ssZ")
Try this:
if(DateTime.TryParseExact(txtDateBorrowed.Text, "M/d/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out tempDateBorrowed))
{
TimeSpan span = DateTime.Today - tempDateBorrowed;
}

date conversion error

I am developing windows application.
In that i have date in the string format as>> fileDate="15/03/2013"
I want it to be get converted into date format as my database field is datetime.
I used following things for it>>
DateTime dt = DateTime.ParseExact(fileDate, "yyyyy-DD-MM", CultureInfo.InvariantCulture);
DateTime dt = DateTime.Parse(fileDate);
Both of these methods proved failure giving me error>>
String was not recognized as a valid DateTime.
What can be mistake?
Is there another technique to do that?
string fileDate = "15/03/2013";
DateTime dt = DateTime.ParseExact(fileDate, "dd/mm/yyyy", CultureInfo.InvariantCulture);
You have to give the date format according to the date string you have to ParseExact. You can see more on Custom DateTime format - MSDN
Change
"yyyy-MM-dd HH:ss"
To
"dd/MM/yyyy"
Your code would be
DateTime dt = DateTime.ParseExact(fileDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
You should do this:
DateTime dt = DateTime.ParseExact(fileDate, "dd/MM/yyyy",CultureInfo.InvariantCulture);
You must pass in the string for the format ("dd/MM/yyyy") in the same style that you pass in the string fileDate.
u may try with this
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = dateFormat.parse("ur_dateString")
In your current code you are using format "yyyyy-DD-MM" which is wrong since date part require lower case d not upper case D. , Also for year part you are specifying 5 ys, it should be 4, like yyyy, the order according to your date string should be: "dd/MM/yyyy". To be on the safe side you can even use "d/M/yyyy", which would work for single digit or double digit day/month.
So your code should be:
string fileDate="15/03/2013";
DateTime dt = DateTime.ParseExact(fileDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
You can see more on Custom DateTime format - MSDN
It's because string "15/03/2013" cannot really be parsed as DateTime with format string "yyyy-MM-dd HH:ss".

Categories