I have console application that accepts date as parameter. However, the date is passed as a string in this format:
string dt = DateTime.Now.ToString("yyyyMMdd");
Once the date is entered I need to programmatically get day - 1 from the entered date. Since this is a string, I cannot do any calculation.
For example, user enters:
20141023
I need to subtract a day from the date to get:
20141022
I did a quick fix to solve my immediate need, however, this is not the right way to do it and it has a bug:
int yt = Int32.Parse(dt) - 1;
And then I turn around and convert it yt.ToString()
The above solution will not work if it's the 1st of the month.
Is there a way I can programmatically get yesterday's date in the format (yyyyMMdd) without changing the format and possibly not using the TimeSpan?
Why don't parse the input into a DateTime object? Then you can use the DateTime.AddDays(-1)
For example:
var inputDate = DateTime.ParseExact("20141022", "yyyyMMdd", CultureInfo.InvariantCulture); // change "20141022" into the inputted value
var yesterday = inputDate.AddDays(-1);
var yesterdayString = yesterday.ToString("yyyyMMdd"); // this will be yesterdays date, in the string format
Try this...
DateTime data = DateTime.ParseExact("20141023", "yyyyMMdd", CultureInfo.InvariantCulture);
Console.WriteLine("{0} - {1}", data, data.AddDays(-1).ToString("yyyyMMdd"));
Would this work for you ?
string newDateTimeStr = (DateTime.Today.AddDays(-1)).ToString("yyyyMMdd");
EDIT:
for the date entered by the user:
string txtInputDate = Console.ReadLine();
DateTime dateTime = new DateTime(txtInputDate).ToLocalTime();
string newDateTimeStr = (dateTime.AddDays(-1)).ToString("yyyyMMdd");
Related
I have a date in this format "2017-03-29" and time like "09:30", How do I conver toDatetime.
Following is how I have
string date = "2017-03-29";
string time = "09:30"
I need to convert this to DateTime in c#.
I also need to compare this converted DateTime with current dateTime, I will be using this in comparison in Linq
Use DateTime.ParseExact. Also your problem statement and code shown have nothing to do with Linq. The code below assumes the hours are in 24 hour format, adjust accordingly if that is not the case and provide an am/pm flag.
string date = "2017-03-29";
string time = "09:30";
var dateTime = DateTime.ParseExact(date+time, "yyyy-MM-ddHH:mm", null);
I would say the same as #Sam, but I don't have enough reputation to comment.
string date = "2017-03-29";
string time = "09:30";
string dateTimeString = string.Format("{0} {1}", date, time);
DateTime dateTime = DateTime.ParseExact(dateTimeString, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
Note that the Kind of the resulting DateTime is DateTimeKind.Unspecified. Convert it as necessary.
Using the variables provided:
string dateTime = date + " " + time;
DateTime d = Convert.ToDateTime(dateTime);
All of my friend.
I want to convert informal string to dateTime in c#. Here my string value is "01042016".How can convert? can i need another step to change DateTime.
This is my code:
string FinancialYear = "01042016-31032017";
string[] splitDate = FinancialYear.Split('-');
DateTime startDate = Convert.ToDateTime(splitDate[0].ToString(),"dd/MM/yyyy"));
As we can see that the input date will be in the format ddMMyyyy so here the best option for converting the input to DateTime object is DateTime.TryParseExact the code for this will be :
string FinancialYear = "01042016-31032017";
string[] splitDate = FinancialYear.Split('-');
DateTime startDate ;
if(DateTime.TryParseExact(splitDate[0],"ddMMyyyy",CultureInfo.InvariantCulture,DateTimeStyles.None,out startDate))
{
// Proceed with the startDate it will have the required date
}
else
// Show failure message
This will create an Enumerable where index 0 is the first date and index 1 is the second date.
string FinancialYear = "01042016-31032017";
var dateRange = FinancialYear.Split('-')
.Select(d => DateTime.ParseExact(d, "ddMMyyyy", CultureInfo.InvariantCulture);
If you are not sure of the format your best bet is using DateTime.Parse() or DateTime.TryParse()
You are not 100% guaranteed that the date will be parsed correctly, especially in cases where the day and month numbers could be in the wrong order.
It is best to specify a required date format if you can so you can be sure the date was parsed correctly.
if you string is in static format, you can convert it by reconvert it to valid string format first such as
string validstring = splitDate[0].ToString().Substring(4,4)+"-"+splitDate[0].ToString().Substring(2,2) +"-"+ splitDate[0].ToString().Substring(0,2);
DateTime startDate = Convert.ToDateTime(validstring,"dd/MM/yyyy"));
I have one field in database in this format: 2013-06-18 17:00:00.000
and second field Duration in this format: 3000 (this represents seconds, so it is 50 minutes)
I need to subtract those two fields and to set in another field result which will be: 2013-06-18 16:10:00.000
One addition is that they both can be retrieved from database in string format only. So they are both strings.
Thanks
First you need to Parse the datetime. Then subtract using AddSeconds:
var date = DateTime.Parse("2013-06-18 17:00:00.000");
var newDate = date.AddSeconds(int.Parse("-3000"));
You can use newDate.ToString() to get the date as a string.
You can find the documentation for DateTime here.
Update: Changed seconds to a string value. Which uses Parse to convert to an integer.
You can subtract to the datetime object. (if is a DateTime Type) if not, you should parse.
To handle errors, I would recommend to use DateTime.tryParse(value, out dateTime);
DateTime parsedDateFromBD;
if(DateTime.tryParse("2013-06-18 17:00:00.000", out parsedDateFromBD)
{
// do Stuff
}
else
{
// do something else
}
if you get it as a datetime from the db you can simply:
var calcDate1 = dateFromBD.addSeconds(3000); //to Add
var calcDate2 = dateFromBD.addSeconds(-3000); //to subtract
Cheers
Ricardo
In addition to the other answers here is how to parse the newDate to string that mach the required output
string date = "2013-06-18 17:00:00.000";
string duration = "-3000";
int durationSeconds = int.Parse(duration);
var newDate = DateTime.Parse(date).AddSeconds(durationSeconds).ToString("yyyy-MM-dd HH:mm:ss.fff");
The output is
//2013-06-18 16:10:00.000
Here you can find more about DateTime.ToString()
I have a date string with dd/mm format like 06/03.Now i have to store this string into mysql table column with DATETIME format.
I am getting the problem as How can i add the current year generically because i don't want to hard code it.Subsequently how will i convert it into MySql DATETIME format for saving it.
Please help me .
You can use Parse method of DateTime:
DateTime dateTime = DateTime.Parse("06/03");
UPDATE
For your comment:
Also after parsing into DateTime i am getting date correct but time i
dont want to be 12:00:00 AM instead i want it to be 00:00:00.
12:00:00 AM corresponds to 00:00:00 only. You can verify that by getting Hour property which will return 0 and also TimeOfDay will too return 00:00:00.
Even if you try to parse exact date, it also creates the same format.
DateTime dateTime = DateTime.ParseExact("06/03 00:00:00", "dd/MM hh:mm:ss",
CultureInfo.InvariantCulture);
And you don't need conversion from DateTime object to SQL compliant DateTime object. You can pass the .Net object to SQL writer.
Consider the code:
C#
string s = "06/03";
System.DateTime dateNow = Convert.ToDateTime(s);
will give the output as you required
in VB.Net :
Dim s As String = "06/03"
Dim dateNow As Date = CDate(s)
MsgBox(dateNow)
You could do something like
var some_date = "06/03";
var year = DateTime.Now.Year;
var option = some_date+"/"+year;
Or use any of the string formats to bend it to your needs
More on date string format can be found on this MSDN page.
Edit:
If you want zeroes in the time, like your comment said, you can usit Rohit vats answer and do:
DateTime dateTime = DateTime.Parse("06/03");
var s1 = dateTime.ToString("MM/dd/yy 00:00:00");
// Output: 03/06/14 00:00:00
var s2 = dateTime.ToString("MM/dd/yyyy 00:00:00");
// Output: 03/06/2014 00:00:00
I have a textfield that has a date with the format "12/23/2010".Is there away for me to get the number 23 using watin ie get number from textfield;i'm gonna use it like this.
1.Get datetime 12/23/2010 and get number '23'
2.substract 2 from 23 and store it somewhere[ie: 23 - 2 = 21]
3.Insert the new datetime number [ie:12/21/2010 ]
string myDate = browser.TextField(Find.ByName("myTextField")).Value;
DateTime time = = new DateTime();
time2 = time - 2;
browser.TextField(Find.ByName("myTextField")).TypeText(time2);
Is this possible?or should i be looking to another way.Ask the user to insert the data instead.
You should use DateTime.Parse, DateTime.TryParse, DateTime.ParseExact or DateTime.TryParseExact to parse from text to a DateTime.
If a failure to parse indicates a failure in the code somewhere (which is probably the case here, given that it's a test) I suspect DateTime.ParseExact is the most appropriate approach, providing the expected format, culture etc.
if what you want is to subtract 2 days from a date I would do it like this:
DateTime dt = DateTime.Parse(myDate)-TimeSpan.FromDays(2);
//its steps 1,2 & 3 in one easy to read line :)
This is of course if you are sure the string you have IS a valid date. If it might not be, then you should do what the Skeet recommends, which is using first a try parse, checking if the return value is true, and if it is, then do the rest, and if it is not, send an error message.
consider writing
DateTime dt = Convert.ToDateTime(myDate);
DateTime dtNew = new DateTime(dt.Year, dt.Month, dt.Day - 2);
browser.TextField(Find.ByName("myTextField")).TypeText(dtNew.ToShortDateString());
Try getting the value of the date as string
Convert it to datetime and use AddDays we can use negative or positive value
And insert it into textbox
string myDate = this.Elements.textfield.Value;
DateTime dt = Convert.ToDateTime(myDate);
DateTime dtNew = dt.AddDays(-3);
this.Elements.ChangeDateActive.TypeText(dtNew.ToShortDateString());
That's it thanks