Not getting correct date from DateTime in c# - c#

I need only date in the yyyy-MM-dd format, but I'm getting (20/03/2018 0:00:00) date in wrong format.
var d = Convert.ToDateTime("2018-03-20T00:00:00.000",CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
var finaldate = DateTime.TryParseExact(d, "yyyy-MM-dd", null);
Output i am getting --20/03/2018 0:00:00
expected -- 2018-03-20

I will try to explain what the others meant when they wrote "DateTime has no format".
DateTime is a C# type that has properties for year, month, day, etc.
If you want to print a DateTime, you first have to convert it to a string. During this conversion, you can define the output format.
Also, if you parse a string into a DateTime, you can define the expected input format.
This is what the "Standard Date and Time Format Strings" / "Custom Date and Time Format Strings" are for.
An example:
string d = Convert.ToDateTime("2018-03-20T00:00:00.000",CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
DateTime finaldate = DateTime.TryParseExact(d, "yyyy-MM-dd", null); // not a string!
int year = finadate.Year; // year == 2018 (a number!)
int month = finaldate.Month; // month == 3 (a number again!)
string isoFormat = finaldate.ToString("yyyy-MM-dd"); // isoFormat == "2018-03-20"
string usFormat = finaldate.ToString("MM/dd/yyyy"); // usFormat == "03/20/2018"
// and so on...
Note that if you just call ToString() without specifying any format, the result will depend on the culture of the current thread (probably "en-Us" judging from the output you have shown). See DateTime.ToString Method.

DateTime always returns DateTime object with the time part.
To get expected output, you have to return string eg. DateTime.Now.ToString("dd-MM-yyyy")

Related

C# parse DateTime String to time only

I am new to C# and I have a string like "2021-06-14 19:27:14:979". Now I want to have only the time "19:27:14:979". So do I parse the string to a specific DateTime format and then convert it back to a string or would you parse or cut the string itself?
It is important that I keep the 24h format. I don't want AM or PM.
I haven't found any solution yet. I tried to convert it to DateTime like:
var Time1 = DateTime.ParseExact(time, "yyyy-MM-dd HH:mm:ss:fff");
var Time2 = Time1.ToString("hh:mm:ss:fff");
But then I lost the 24h format.
Your code is almost working, but ParseExact needs two additional arguments and ToString needs upper-case HH for 24h format:
var Time1 = DateTime.ParseExact("2021-06-14 19:27:14:979", "yyyy-MM-dd HH:mm:ss:fff", null, DateTimeStyles.None);
var Time2 = Time1.ToString("HH:mm:ss:fff");
Read: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#uppercase-hour-h-format-specifier
Instead of passing null as format provider(means current culture) you might want to pass a specifc CultureInfo, for example CultureInfo.CreateSpecificCulture("en-US").
You can just split it at the blank and take the last part like this
var timestamp = "2021-06-14 19:27:14:979";
var timePart = timestamp.Split(' ')[1];
in your case that seems easier than parsing into a DateTime and back into a string.

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

Convert to dateTime from string (arabic culture to english)

string strHijdt ="29-02-1435";
DateTime hdt = DateTime.ParseExact(strHijdt, "dd/MMM/yyyy HH:MI24",
CultureInfo.InvariantCulture);
Getting error while convert to string("29-02-1435") to datetime
2/1435 has 28 days only
so, below will work
string aa="28-02-1435";
DateTime hdt = DateTime.ParseExact(aa, "dd-MM-yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(hdt.ToLongDateString());
DEMO
since you have given input as 29-02-1435 even you provide correct date time format (dd-MM-yyyy) you will get error for the invalid date
Two problems here:
1. As mentioned above, expected format for does not match string (there is no time, different separator)
2. If your date string is in Hijri calendar, you should either provide correct culture explicitly or use system culture (pass null for IFormatProvider):
string strHijdt = "29-02-1435";
var culture = CultureInfo.GetCultureInfo("ar-SA");
DateTime hdt = DateTime.ParseExact(strHijdt, "dd-MM-yyyy", culture);

c# show only Time portion of DateTime

I have a date that shows up as 10/18/2011 3:12:33 PM
How do I get only the time portion of this datetime?
I am using C#.
I tried:
string timeval = PgTime.ToShortTimeString();
but that did not work as Intellisense only showed ToString();
Assuming that
DateTime PgTime;
You can:
String timeOnly = PgTime.ToString("t");
Other format options can be viewed on MSDN.
Also, if you'd like to combine it in a larger string, you can do either:
// Instruct String.Format to parse it as time format using `{0:t}`
String.Format("The time is: {0:t}", PgTime);
// pass it an already-formatted string
String.Format("The time is: {0}", PgTime.ToString("t"));
If PgTime is a TimeSpan, you have a few other options:
TimeSpan PgTime;
String formattedTime = PgTime.ToString("c"); // 00:00:00 [TimeSpan.ToString()]
String formattedTime = PgTime.ToString("g"); // 0:00:00
String formattedTime = PgTime.ToString("G"); // 0:00:00:00.0000000
If you want a formatted string, just use .ToString(format), specifying only time portions. If you want the actual time, use .TimeOfDay, which will be a TimeSpan from midnight.
DateTime PgTime = new DateTime();
var hr = PgTime.Hour;
var min = PgTime.Minute;
var sec = PgTime.Second;
//or
DateTime.Now.ToString("HH:mm:ss tt") gives it to you as a string.
Don't now nothing about a class named PgTime. Do now about DateTime, though.
Try
DateTime instance = DateTime.Now ; // current date/time
string time = instance.ToString("t") ; // short time formatted according to the rules for the current culture/locale
Might want to read up on Standard Date and Time Format Strings and Custom Date and Time Format Strings
In C# 10 you can use TimeOnly.
TimeOnly date = TimeOnly.FromDateTime(PgTime);

How to get today's date in mm/dd/yyyy format into a datetime variable in c#

I want today's date in mm/dd/yyyy format from a DateTime variable. How to get it?
I need to check this with some date variable so it must be also in date variable format?plz help
Ex: i need to get today date in mm/dd/yyyy format and i already date which is datetime datatype in mm/dd/yyyy format and i have to compare them
You should use DateTime.Today:
DateTime today = DateTime.Today; // As DateTime
string s_today = today.ToString("MM/dd/yyyy"); // As String
Edit: You edited your post to add another question, so here comes my edit to supply at least some sort of answer.
Update While you can use DateTime.Compare() you should use plain comparisson:
if(today < otherdate)
{
// Do something.
}
Alternatively, you can use DateTime-variables to check against other DateTime-variables using the DateTime.Compare() method. Both otpions will work and it comes down to preference and what you want to do with the result.
int result = DateTime.Compare(today, otherdate);
if(result < 0)
MessageBox.Show("Today is earlier than the 'otherdate'");
elseif(result > 0)
MessageBox.Show("Today is later than the 'other date'");
else
MessageBox.Show("Dates are equal...");
string datestring = DateTime.Now.ToString("MM/dd/yyyy");
MSDN say: Custom Date and Time Format Strings
To convert DateTime variable to string in the specified format:
DateTime d = ...;
string s = d.ToString("MM/dd/yyyy");
If you want to compare only date part of DateTime, not time part:
DateTime d1 = DateTime.Parse("10/10/2011");
DateTime d2 = DateTime.Parse("01/01/2011");
if (d1.Date > d2.Date)
{
// do the stuff
}
DateTime.Now.ToString("MM/dd/yyyy");
DateTime.Today.ToString("MM/dd/yyyy");
DateTime.Parse is what you are looking for...

Categories