To Get Date From DateTime Variable - c#

I have a variable testDate which contains value {01/02/2016 AM 12:00:00}. I need to get only date part from the set. For that I used below code:
var testDate = startDate.AddDays(i);
var testDateOnly = testDate.Date;
But it returns the same {01/02/2016 AM 12:00:00}.

The date variable will contain the date, the time part will be 00:00:00
http://msdn.microsoft.com/en-us/library/system.datetime.date.aspx
// The date with time component
var testDate = startDate.AddDays(i);
// Get date-only portion of date, without its time (ie, time 00:00:00).
var testDateOnly = testDate.Date;
// Display date using short date string.
Console.WriteLine(testDateOnly.ToString("d"));
// OUTPUT will be 1/2/2016

var testDate = startDate.AddDays(i);
string dateOnlyString = testDate.ToString("dd-MM-yyy");
"dd-MM-yyy" this will be the Date Format of the output string, You can choose the format as per your requirements.
You can use the following also for formatting:
dateOnlyString = d.ToString("M/d/yyyy"); // "3/9/2008"
dateOnlyString = d.ToString("MM/dd/yyyy}"); // "03/09/2008"
// day/month names
dateOnlyString = d.ToString("ddd, MMM d, yyyy}"); // "Sun, Mar 9, 2008"
dateOnlyString = d.ToString("dddd, MMMM d, yyyy}"); // "Sunday, March 9,2008"
// two/four digit year
dateOnlyString = d.ToString("MM/dd/yy}"); // "03/09/08"
dateOnlyString = d.ToString("MM/dd/yyyy}"); // "03/09/2008"

You need to convert the Date in to String type using this,
var testDate = startDate.AddDays(i);
var testDateOnly = testDate.Date.ToShortDateString(); //string
or
var testDateOnly = testDate.Date.ToString("dd/MM/yyyy");
or
var testDateOnly = testDate.Date.ToString("d");
Check it here.
Find the more about Standard Date and Time Format Strings
You will get the dd-MM-yyyy format by doing this.

Related

DateTime parsing - unexpected result

I have datetime string
dateStr = "2017-03-21T23:00:00.000Z";
then I am calling
var date = DateTime.Parse(dateStr);
and unexpectedly my date equals
22.03.2017 00:00:00
I expected it to be 21.03.2017
What's going on here?
DateTime.Parse() is locale specific and will take into account your local time zone when parsing dates.
If you are in CET (Central European Time) during the winter your offset is one hour ahead of UTC. The date given is marked with a Z indicating it is in UTC, so DateTime.Parse() will adjust that to your local timezone.
There is an override that allows you to change that behaviour if you want, by specifying a specific DateTimeStyles enum. DateTimeStyles.AdjustToUniversal is what you are looking for as that should keep the DateTime as UTC.
And if you only want the date part afterwards, you can just call .Date on the DateTime object you got back from Parse()
So, something like this:
var date = DateTime.Parse(dateStr, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).Date;
if the date format does not change then you can use the below code to get date part from date string. But it is a bit risky due to its strict dependency on the input format.
string dateStr = "2017-03-21T23:00:00.000Z";
int year = Int32.Parse(dateStr.Substring(0, 4));
int month = Int32.Parse(dateStr.Substring(5, 2));
int day = Int32.Parse(dateStr.Substring(8, 2));
var date = new DateTime(year, month, day);
Console.WriteLine(date);
Because the format of type 'DateTime' variable is 'YYYY-MM-DD hh:mm:ss'.
If you run this code:
var dt = DateTime.Now;
Console.WriteLine(dt);
You'll see '24/03/2017 12:54:47'
If you have 'YYYY-MM-DD' format, add .ToString("dd-MM-yyyy"), then:
string dateStr = "2017-03-21T23:00:00.000Z";
var date = DateTime.Parse(dateStr).ToString("dd-MM-yyyy");
Result:'24-03-2017'

Assign value of a string (containing date and time) to two different variable (one for Date and one for Time)

I have a string ("CompletionDate") which contains the value "2/28/2017 5:24:00 PM"
Now I have 2 variables (EDate and ETime). I want to assign the Date to EDate (i.e 2/28/2017) and Time to ETime (i.e. 5:24:00 PM).
How can I split the Date and Time from a single string.
Kindly Help.
My approach right now is like :
string CompletionDate = string.Empty;
string ProjectEDate = string.Empty;
string ProjectETime = string.Empty;
CompletionDate = "2017-03-29 12:58:00";
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd", CultureInfo.CreateSpecificCulture("en-us"));
DateTime dt1 = DateTime.ParseExact(CompletionDate, "HH:mm:ss", CultureInfo.CreateSpecificCulture("en-us"));
var ProjectEDate = dt.ToString();
var ProjectETime = dt1.ToString();
But its throwing exception that string is not in correct format. Kindly help
#Chris pointed one of your problems, but you have one more. You are passing full date time string and trying to treat it as date or time only, which is not true. Instead I suggest you to parse DateTime object with both date and time, and then take whatever you need from parsed object:
CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-us");
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd HH:mm:ss", enUS);
var ProjectEDate = dt.Date.ToString();
var ProjectETime = dt.TimeOfDay.ToString();
You need to specify the full format as same as the input string to parse method.
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.CreateSpecificCulture("en-us"));
To get results you can use below methods available by default in DateTime.
dt.ToShortTimeString()
"12:58 PM"
dt.ToLongTimeString()
"12:58:00 PM"
dt.ToLongDateString()
"Wednesday, March 29, 2017"
dt.ToShortDateString()
"3/29/2017"
Or you can specify the format to ToString method.
dt.ToString("yyyy-MM-dd")
"2017-03-29"
dt.ToString("HH:mm:ss")
"12:58:00"
DateTime.ParseExact(CompletionDate, "yyy-MM-dd", ...
You are missing 4th 'y' in date format string:
"yyyy-MM-dd"
^
here
and:
String was not recognized as a valid DateTime " format dd/MM/yyyy"
Why do you parse into DateTime and then convert to a string using ToString again? CouldnĀ“t you just simply use String.Split when all you want is to split the time from the day and you know the exact format?
var CompletionDate = "2017-03-29 12:58:00";
var tmp = CompletionDate.Split(' ');
var ProjectEDate = tmp[0];
var ProjectETime = tmp[1];

Convert string to datetime and remove the time part from the date

I have a date returned from database which includes even the time. i want to remove the time part of the string and send only the date. my code is as given below
DateTime Var = new DateTime();
Var = Convert.ToDateTime(Dset.Tables[1].Rows[i]["Date"]);
Var = Var.ToShortDateString();
DateTime Var = Convert.ToDateTime(Dset.Tables[1].Rows[i]["Date"]).Date; //only date part
string date = Var.ToShortDateString();
it will store only date in DateTime object
Var = Var.Date;
time will be 00:00:00
or you can store it as string:
var dateString = Var.ToShortDateString();
you can custom your date string format by using DateTime.ToSting("your format") method.
then the code will be like this.
DateTime Var = new DateTime();
Var = Convert.ToDateTime(Dset.Tables[1].Rows[i]["Date"]);
Var = Var.ToString("yyyy-MM-dd");
you can also use SubString() method to gain the date part of the datetime string.

Converting ToShortDateString converted datetime back to datetime

how can a date like '20/11/2013' - string be converted to this format
2013-11-20 00:00:00.000 in c# using
DateTime.ParseExact or any other function.
Using DateTime.ParseExact you can do it as mentioned below :
var stringToConvert = "20/11/2013";
var convertedDate = DateTime.ParseExact(stringToConvert, "dd/MM/yyyy", CultureInfo.InvariantCulture);
// dd : date
// MM : minute
// yyyy : year
// hh : hour
// mm : minute
// ss : second
var dateFormatMMddYYYY = convertedDate.ToString("MM-dd-yyyy");
var dateFormatddMMYYYY = convertedDate.ToString("dd-MM-yyyy");
var dateFormatyyyyMMdd = convertedDate.ToString("yyyy-MM-dd");
Note : Before converting to datetime make sure that your string is able to convert to the datetime.
You can use Datetime.TryParse function for that.
You can use the DateTime.TryParse(...) method.
var dtString = "01/01/2000 01:00:00 AM";
DateTime dt;
var converted = DateTime.TryParse(dtString, out dt);
if (converted) {
// Converted okay.
var newFormat = dt.ToString("yyyy/MM/dd hh:mm:ss");
// Outputs: 2001/01/01 01:00:00
} else {
// Failed to convert.
}
This is handy as it'll allow you to check if the DateTime string specified converted okay.
string originalShortDateTime = "20/11/2013";
string inputFormat = "dd/MM/yyyy";
DateTime result = DateTime.ParseExact(originalShortDateTime,
inputFormat, CultureInfo.InvariantCulture); //or a specific culture
We'll then output the preferred format using a DateTime.ToString() with argument:
string outputDateString = result.ToString("yyyy-MM-dd hh:mm:ss.fff");

Min Date and Max date

I have a list of dates as below
List<string> nameList = new List<string>();
nameList.Add("20120618PM");
nameList.Add("20120622PM");
nameList.Add("20120622AM");
nameList.Add("20120628PM");
nameList.Add("20120702PM");
nameList.Add("20120629AM");
nameList.Add("20120629PM");
I want to find MAXDATE and MIN DATE from the list .Please let me know how can i proceed.
Regards,
Channa
What format is that? "yyyyMMddtt"?
There is AM PM with date. There is no time to accompany AM/PM. So I am assuming AM is 00:00:00 and PM is 12:00:00
First correct your format then use this
List<DateTime> temp = nameList.Select(x =>
DateTime.ParseExact(x, "yyyyMMddtt", CultureInfo.InvariantCulture)).ToList();
Then
temp.Min("yyyyMMddtt");
temp.Max("yyyyMMddtt");
If the date format is yyyyMMdd then is is sortable as strings even with AM/PM
nameList.Max()
If you have a year plus hours/minutes and AM/PM then you must parse to DateTime. I recommend parsing regardless, as suggested in other answers.
// 1. Convert your string list to datetimes
IEnumerable<DateTime> dates = nameList.Select(m => DateTime.Parse(m, yourFormatProvider));
// 2. Get first and last date
DateTime maxDate = dates.Max();
DateTime minDate = dates.Min();
If I had to guess, which it seems I do. I would do this
var dates = nameList.ConvertAll(s => {
var dateString = s.SubString(6);
var timeString = s.SubString(7, 2);
var date = DateTime.Parse(dateString);
if (timeString == "PM")
{
date = date.AddHours(12);
}
return date;
});
var max = date.Max();
var min = date.Min();
Since you have specified your format as yyyyMMdd in your comment, you need to trim PM and AM from the string
List<DateTime> dateList =
nameList.Select(x =>
DateTime.ParseExact(
x.TrimEnd("PM".ToCharArray()).TrimEnd("AM".ToCharArray()),
"yyyyMMdd",
CultureInfo.InvariantCulture)
).ToList();
var Minimum = dateList.Min();
var Maximum = dateList.Max();
Console.WriteLine(Minimum.ToString());
Console.WriteLine(Maximum.ToString());
This will give you:
6/18/2012 12:00:00 AM 7/2/2012 12:00:00 AM

Categories

Resources