1000 Days after Birth - c#

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. :)

Related

Convert to DateTime from two string variables in 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 !

How to solve leap year in Persian calendar

Today is 1397/02/29 (yyyy/mm/dd) in Persian calendar.
and my website reports his error:
'Year, Month, and Day parameters describe an un-representable DateTime.'
I used datetime2 in SQL database and saved Persian date in it by converting this date:
PersianCalendar pc = new PersianCalendar();
DateTime dateTime = DateTime.Now;
return new DateTime(pc.GetYear(dateTime), pc.GetMonth(dateTime), pc.GetDayOfMonth(dateTime), pc.GetHour(dateTime), pc.GetMinute(dateTime), pc.GetSecond(dateTime), 0);
What should i do?
Quite ignorant here... but in general you should treat "internally" (in the program and in the db) all the dates using the normal Proleptic Gregorian calendar (per ISO 8601), and reformat them to Persian only when you read input from the user/write output to the user. There is a PersianCalendar class in .NET that helps converting persian-to-american and back.
For example
var pc = new PersianCalendar();
DateTime dt = pc.ToDateTime(1397, 02, 29, 0, 0, 0, 0);
works correctly, but if you take a look at the dt variable you'll see that it shows as 2018-05-19.
If doing a ToString() on a DateTime variable you see a persian date, then you probably have an error in your code. If doing a SELECT on a table in the db you see a persian date, then you probably have an error in your db.
The interesting paradox is that internally both .NET and SQL save dates as a single number, representing how many units of time (where in .NET a unit of time is 100 nanoseconds, in SQL it is 1 day) have passed from a "zero point" to the date, but then all their "standard" methods for handling dates (both in .NET and SQL) use the gregorian calendar (because it is the most used in the world).
Use this solution
static void Main(string[] args)
{
Console.WriteLine(GetIsLeapDateTime(1358));
Console.WriteLine(GetIsLeapDateTime(1359));
Console.WriteLine(GetIsLeapDateTime(1360));
Console.WriteLine(GetIsLeapDateTime(1361));
Console.WriteLine(GetIsLeapDateTime(1362));
Console.WriteLine(GetIsLeapDateTime(1363));
Console.WriteLine(GetIsLeapDateTime(1364));
Console.WriteLine(GetIsLeapDateTime(1365));
Console.WriteLine(GetIsLeapDateTime(1366));
Console.ReadLine();
}
private static bool GetIsLeapDateTime(int year)
{
PersianCalendar pc = new PersianCalendar();
return pc.IsLeapYear(year);
}
in Jalali calendar
It seems that every 33 years, leap years happen once every 5 years and then back to once every 4 years.
1370 is a leap year, but 1374 is not a leap year, and instead, 1375 is a leap year. Also, 1403 is not a leap year and 1407 is not a leap year, and instead, 1408 leap years.

DateTime.Date get me Date and 12:00 AM

I have already seen this.
I am going to get only Date from a DateTime variable and in this way I used this code:
DateTime Start = GetaDateTime();
String Day = Start.ToString("yyyy/MM/dd");
DateTime d = Convert.ToDateTime(Day);
But when I use d.Date it gives me '2014-08-23 12:00 AM'
Actually I should not get 12:00AM any more????
Actually I should not get 12:00AM any more????
Why not? A DateTime has no notion of whether it's meant to be a date or a date and time, or any sort of string formatting. It's just a point in time (and not even quite that, given the odd Kind part of it).
Note that a simpler way of getting a DateTime which is the same as another but at midnight is just to use Date to start with:
DateTime start = Foo();
DateTime date = start.Date;
No need for formatting and then parsing.
There's no .NET type representing just a date. For that, you'll want something like my Noda Time project, which has a rather richer set of date/time types to play with.

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.

Converting a year from 4 digit to 2 digit and back again in C#

My credit card processor requires I send a two-digit year from the credit card expiration date. Here is how I am currently processing:
I put a DropDownList of the 4-digit year on the page.
I validate the expiration date in a DateTime field to be sure that the expiration date being passed to the CC processor isn't expired.
I send a two-digit year to the CC processor (as required). I do this via a substring of the value from the year DDL.
Is there a method out there to convert a four-digit year to a two-digit year. I am not seeing anything on the DateTime object. Or should I just keep processing it as I am?
If you're creating a DateTime object using the expiration dates (month/year), you can use ToString() on your DateTime variable like so:
DateTime expirationDate = new DateTime(2008, 1, 31); // random date
string lastTwoDigitsOfYear = expirationDate.ToString("yy");
Edit: Be careful with your dates though if you use the DateTime object during validation. If somebody selects 05/2008 as their card's expiration date, it expires at the end of May, not on the first.
1st solution (fastest) :
yourDateTime.Year % 100
2nd solution (more elegant in my opinion) :
yourDateTime.ToString("yy")
The answer is already given. But here I want to add something.
Some person told that it did not work.
May be you are using
DateTime.Now.Year.ToString("yy");
that is why it is not working. I also made the same the mistake.
Change it to
DateTime.Now.ToString("yy");
This should work for you:
public int Get4LetterYear(int twoLetterYear)
{
int firstTwoDigits =
Convert.ToInt32(DateTime.Now.Year.ToString().Substring(2, 2));
return Get4LetterYear(twoLetterYear, firstTwoDigits);
}
public int Get4LetterYear(int twoLetterYear, int firstTwoDigits)
{
return Convert.ToInt32(firstTwoDigits.ToString() + twoLetterYear.ToString());
}
public int Get2LetterYear(int fourLetterYear)
{
return Convert.ToInt32(fourLetterYear.ToString().Substring(2, 2));
}
I don't think there are any special built-in stuff in .NET.
Update: It's missing some validation that you maybe should do. Validate length of inputted variables, and so on.
Use the DateTime object ToString with a custom format string like myDate.ToString("MM/dd/yy") for example.
//using java script
var curDate = new Date();
var curYear = curDate.getFullYear();
curYear = curYear.toString().slice(2);
document.write(curYear)
//using java script
//using sqlserver
select Right(Year(getDate()),2)
//using sql server
//Using c#.net
DateTime dt = DateTime.Now;
string curYear = dt.Year.ToString().Substring(2,2).ToString() ;
//using c#.net
Starting with c# 6.0 you can use the built-in composite formatting in string interpolation on anything that processes c#, like an MVC Razor page.
DateTime date = DateTime.Now;
string myTwoDigitYear = $"{date:yy};
No extensions necessary. You can use most of the standard date and time format strings after the colon after any valid DateTime object inside the curly brackets to use the built-in composite formatting.
At this point, the simplest way is to just truncate the last two digits of the year. For credit cards, having a date in the past is unnecessary so Y2K has no meaning. The same applies for if somehow your code is still running in 90+ years.
I'd go further and say that instead of using a drop down list, let the user type in the year themselves. This is a common way of doing it and most users can handle it.
I've seen some systems decide that the cutoff is 75; 75+ is 19xx and below is 20xx.
DateTime.Now.Year - (DateTime.Now.Year / 100 * 100)
Works for current year. Change DateTime.Now.Year to make it work also for another year.
The answer is quite simple:
DateTime Today = DateTime.Today;
string zeroBased = Today.ToString("yy-MM-dd");
Why not have the original drop down on the page be a 2 digit value only? Credit cards only cover a small span when looking at the year especially if the CC vendor only takes in 2 digits already.
Here is a link to a 4Guys article on how you can format Dates and Times using the ToString() method by passing in a custom format string.
http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=181
Just in case it goes away here is one of the examples.
'Create a var. named rightNow and set it to the current date/time
Dim rightNow as DateTime = DateTime.Now
Dim s as String 'create a string
s = rightNow.ToString("MMM dd, yyyy")
Since his link is broken here is a link to the DateTimeFormatInfo class that makes those formatting options possible.
http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx
It's probably a little more consistent to do something like that rather than use a substring, but who knows.
This is an old post, but I thought I'd give an example using an ExtensionMethod (since C# 3.0), since this will hide the implementation and allow for use everywhere in the project instead or recreating the code over and over or needing to be aware of some utility class.
Extension methods enable you to "add" methods to existing types
without creating a new derived type, recompiling, or otherwise
modifying the original type. Extension methods are a special kind of
static method, but they are called as if they were instance methods on
the extended type. For client code written in C# and Visual Basic,
there is no apparent difference between calling an extension method
and the methods that are actually defined in a type.
public static class DateTimeExtensions
{
public static int ToYearLastTwoDigit(this DateTime date)
{
var temp = date.ToString("yy");
return int.Parse(temp);
}
}
You can then call this method anywhere you use a DateTime object, for example...
var dateTime = new DateTime(2015, 06, 19);
var year = cob.ToYearLastTwoDigit();
This seems to work okay for me.
yourDateTime.ToString().Substring(2);
Even if a builtin way existed, it wouldn't validate it as greater than today and it would differ very little from a substring call. I wouldn't worry about it.

Categories