Convert to DateTime from two string variables in C# - c#

I want to convert two string variables to a DateTime variable.
So something like this...
string day = "05";
string month = "11";
Convert.ToDateTime(day + month + "0000");
This will then be uploaded to a SQL server smalldatetime datatype.
Is there any way to do this? I've seen some people use ParseExact but they use it with a perfect date format, never creating it from two strings like I want to do. Does anyone know how to do this?

You can try this:
string day = "05";
string month = "11";
string year = "0001";
DateTime dt =
DateTime.ParseExact(day + "-" + month + "-" + year, "dd-MM-yyyy", CultureInfo.InvariantCulture);
But year must not be 0.
'0001' year represent first year only. so you can say 0 years has been passed till this date.
UPDATE
as jimi mentioned below
smalldatetime goes from 1900-01-01 to 2079-06-06. The OP will have to safe-check this range before converting.
you would have to be careful while parsing string into Date, if you are going with smalldatetime, you are limited with range of "1900-01-01 to 2079-06-06" so your DateTime cannot have year 0001 at that time.

The day and month only matter as it represents when a school year ends, the application I'm making will take the month and day.
If you are not using any specific year, don't use a date time type!
The dateTime format will need a year, as already stated, and using a fake one will just convey a lot of false information with it (for instance, the day of week, Monday, Tuesday, ...). Of course you don't want to use it, and you probably won't, but you could be victim of some display bug and other unwanted consequences.
I'd suggest you simply use two integer fields, one for the day and one one for the month.
For validation purpose, you could internally use some dateTime following the other accepted answer for instance. That would be one way to prevent "31st April".
But I recommend you to avoid storing a fake year in your db, along with a complicated type, that could cause you more trouble than needed in the long run.
On the other hand, if your app is supposed to refer to the current year or other specific, then use it, don't fake it either !

Related

Why are DateTime Strings 0-padded On One Windows 10 System, but Not On Most Others?

The following code on several machines sets a SQL Server date time string from "NOW" to the same date but at midnight.
DateTime deleteDateThreshold = DateTime.Now;
string deleteDateThresholdS = DateTime.Now.ToString();
deleteDateThresholdS = deleteDateThresholdS.Substring(0, 10) + " " + "00:00:00 AM";
Come to think of it, I could have probably subtracted back to midnight, but I thought this was a faster way.
Then the string gets parsed into a DateTime; and has one day subtracted from it. One one system, the parse blows up, because the Substring encounters an extra character, value of 2, because the date string is not zero-padded (03/04/2020). I finally was able to capture the offending date time; and it's not a DateTime, so the exception should occur.
Here is the code that parses.
deleteDateThreshold = DateTime.Parse(deleteDateThresholdS, us);
deleteDateThreshold = deleteDateThreshold.AddDays(-1);
on most systems, the date string looks like this
"03/04/2020 00:00:00 AM"
However, on the system that throws the exception, the dates are not 0-padded, and the string looks like this:
"3/4/2020 2 00:00:00"
Why is there a 2 in this string, and why are the month and day not 0-padded?
Come to think of it, I could have probably subtracted back to midnight, but I thought this was a faster way.
I'd say that <somedate>.Date or DateTime.Today (thanks, #ckuri) is probably the easiest way to get to the (local) midnight for somedate/today. (Perhaps consider using UtcNow throughout all your systems though)
What the true nature of your problem is, I'm not sure at this point but I'm near certain it wouldn't happen if you kept your dates as dates and didn't convert in and out of strings to manipulate them; SQL Server has date datatypes, that map to CLR datatypes - there shouldn't be any need at all to store, process, transit or manipulate a date as a string in this system at all

1000 Days after Birth

I recently joined a course about C# and I'm really enjoying it but I've got an exercise in which I have to write a date and it should give me back a date after 1000 days. I write some kind of code after a research about the DateTime type but it always gives me a date after 1001 days and not 1000 days. Also I don't want to have time on my final result so I really need help.... I want to apologies if my topic is dumb af... I just made an account here and that's my first post.
So here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1000DaysAfterBirthV2
{
class Program
{
static void Main(string[] args)
{
string birthDate = Console.ReadLine();
DateTime d = Convert.ToDateTime(birthDate).Date;
DateTime.ParseExact(birthDate, "dd-MM-yyyy", null);
DateTime birthday = DateTime.Parse(birthDate);
DateTime after = birthday.AddDays(1000);
Console.WriteLine(after);
}
}
}
As for showing the date without the time, look into the .ToString() method.
after.ToString( "MM/dd/yyyy" );
It is similar to your parsing, MM for month vs mm for minutes. The different representative parts. Pick whatever parts you want in your output. Similar applications of ToString() are used for numeric fields too, such as int, decimal, float to show leading/trailing zeros, decimal precision, etc. All objects have a default "ToString()" method which you can even define your own on your own custom classes when you get that far down...
CLARIFICATION
Calling it is exactly as I have it above based on your reference to the "after" DateTime variable type. ToString() returns a string with a specific format.
When you are calling WriteLine(), that is expecting a string. Since you are passing in your "after" DateTime, the method knows it needs to call the respective .ToString() and implies a default output. All the above sample does is explicitly tells WriteLine to print the date field "after", but using the SPECIFIC format included. If you wanted the date shown in other formats you could do
after.ToString("yyyy-MM-dd") -- year first, then month and day.
after.ToString("dd-MM-yyyy") -- day first, then month, then year
after.ToString("MM-yyyy" ) -- to only show 2-digit month and 4-digit year
What we call the fifth day after a particular event has a date four days later. Friday of next week is the fifth day after Monday, so
DateTime friday = monday.AddDays(4);
The same goes for the thousandth day after an event.
DateTime after = birthday.AddDays(999);
string dateString = Console.ReadLine();
string format= "dd-MM-yyyy";
DateTime result=DateTime.ParseExact(dateString, format,
CultureInfo.InvariantCulture);
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime output = Convert.ToDateTime(result).AddDays(999);
Console.WriteLine(output.ToString("dd-MM-yyyy"));
I think that would do. :)

Compare date less than 3 months

I need to compare whether date is less than 3 months old.
I will get installation date:
DateTime installdate=DateTime.Parse("1/5/2012 8:12:14 PM");
if ((installdate<DateTime.Now.AddMonths(-3)))
{
// do something
}
Is this the best way to compare the dates?
Thanks.
A few things to think about:
"Is date x earlier than 3 months before today" isn't the same as "today is more than 3 months later than date x"; you'll need to make sure you have the exact semantics you want.
Consider what you want to do with the time component - are you interested in dates or dates and times? (Would you expect the condition evaluation to change based on the current time of day?)
Consider time zones: are you interested in "today in the system's current time zone" or some fixed time zone?
Depending on the source of the text data, you should possibly use DateTime.TryParse and you should possibly use DateTime.ParseExact or DateTime.TryParseExact, passing in the expected format (and culture)
Basically, there are various corner cases around date and time behaviour - you should explicitly think about all of these things (some of which are forced upon you if you use Noda Time instead of DateTime, btw :)
Regarding the first point, if the idea is that you get a trial period of three months from the installation date (or something similar), that suggests you should be adding three months to that instead.
I'd also change the variable name and get rid of the redundant parentheses, by the way:
DateTime installationDate = DateTime.Parse("1/5/2012 8:12:14 PM");
DateTime trialPeriodEnd = installationDate.AddMonths(3);
if (trialPeriodEnd > DateTime.Now)
{
// do something
}
Assuming you're storing the installation date yourself somewhere, I would try to store it in some form which is less ambiguous - possibly even storing just a "ticks" value instead of a string. But assuming you are storing it yourself, you shouldn't need to use TryParse - it makes sense to go "bang" if you can't parse the value. I'd use ParseExact, probably with a standard format specifier of "o" (round trip).
DateTime installdate ;
if (DateTime.TryParse("1/5/2012 8:12:14 PM", out installdate))
{
if ((installdate < DateTime.Now.AddMonths(-3))) { }
}
Tryparse is used so as to validate if the date passed in the parameter is valid or invalid

how to add current date time in bigint field

I need to add the current date time in a bigint field in a database... and then display from that only the date in format: october 1, 2009.
I am currently thinking of storing the value in string variable and then converting it to int...
String s = DateTime.Now.ToString();
i dont know what to do next..
please help
You could just store the number of ticks as your bigint value. Ticks represent the number of elapsed 1/10,000 of milliseconds since January 1, 0001.
DateTime.Now.Ticks;
This can always be converted back to a DateTime by using the constructor that accepts a long:
DateTime storedTime = new DateTime(ticksFromDatabase);
To format your date, just use any of the standard date format strings. A custom format string might work better actually, I just perused them and it doesn't look like there's a built in one for the format you want. This should work:
date1.ToString("MMMM d, yyyy", CultureInfo.CreateSpecificCulture("en-US"))
I'd use a smart date key, since it's easier to find that using SQL:
20090927235000
yyyyMMddhhmmss
This way, if you want to find anything that happened on a given day, you could do:
select * from tbl where datecol between 20090927000000 and 20090927240000
Thereby making data validation a lot easier, even if you are using an ORM.

Incomplete DateTime In C#

In C# if I want to parse a datetime, but some times I just have either a date and not a time component or no date but a time component, how would I do this? Usually when you leave out the time component, it automatically assumes that the time is 12:00AM. But I don't want this. If the time component is missing then I just want the DateTime to store a date only and the leave the time component off.
The value of a DateTime internally is just an UInt64 (ulong in C#) that stores the number of ticks since some date in the past, so whether you like it or not, the time component will always be there.
If you only need to display certain parts, just use any of the format strings (examples are for "en-us" culture):
DateTime.Now.ToString("d"); // 5/26/2009
DateTime.Now.ToString("t"); // 4:56 PM
The complete reference: http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
It's not possible to have a DateTime without a time component. You could store a boolean flag along with it in a struct to store data about existence of that component. However, there's no way to use the automatic parsing routine to distinguish between a DateTime string with a time specified as 12:00 PM and a nonexistent one.
If it really bugs you you can always create a wrapper class that can hide the time portions of the datetime class.
No you will have the time component no matter what. The best you can do is access the Date property on your DateTime object if you really have to.
http://msdn.microsoft.com/en-us/library/system.datetime.date.aspx
DateTime by definition stores a date and a time such that it cannot just represent one of them without representing the other. If you only want the date (or only the time), parse out the information you need and discard the rest of it.
As mentioned before DateTime will always have a Date and a Time part of it if you only want a single part use the way described by the others
DateTime date = DateTime.Parse("2009-11-30);
date.Year; = 2009
date.Month; = 11
date.Day; = 30
date.Hour; = 0
and so on
The thing you must be aware is that all of these methods will only return an integer.
If you want to know all the possible ways to parse a string John Sheehan has put together a great Cheat Sheet wit all possible ways to parse and manipulate dates, and other strings for that matter.
You could have a class that stores a DateTime and determines if the time was ever set or if just the date was set and return values accordingly.
Use
DateTime date = new DateTime();
date = DateTime.Parse("1/1/2001");
to set the date, then use
date.ToShortDateString();
or
date.Year;
date.Month;
date.Day;
to get what you need. Hope that helps!
A DateTime object is always stores a date + a time, not just one. You can always choose to work only with the date part, i.e. only use properties like Year, Month, DayOfWeek. But underneath there will aways be some stored time.
It is very dangerous to assume that the date portion of a DateTime is necessarily the date you are expecting. As pointed-out, DateTime always includes and considers the time aspect, even when you don't see it.
This is a big problem when you have data stored in different time-zones (and particularly if knowledge of that offset is not also kept, because it is assumed that what is being stored is a Date, not a date-with-time).
You may store a birthdate as '01/01/2000 00:00:00' during Summer-Time, which then is stored in UCT as '31/12/1999 23:00:00'. When you then read that birth-date later, the date portion is now a day early.
Best to create your own type. Strange that Microsoft didn't think it worth having a Date type.

Categories