DateTime representation and conversion shows the wrong date - c#

I am trying to create a new date from parameters that I receive from a request.
I have this code:
DateTime datefrom = DateTime.ParseExact(DateFromTextBox1.Text,"dd/mm/yyyy", CultureInfo.InvariantCulture).ToUniversalTime();
int hoursFrom = HourFromTextBox1.Text!=String.Empty?Convert.ToInt32(HourFromTextBox1.Text):0;
int minutesFrom = HourFromTextBox1.Text != String.Empty ? Convert.ToInt32(MinuteFromTextBox1.Text) : 0;
date1 = new DateTime(datefrom.Year, datefrom.Month, datefrom.Day, hoursFrom, minutesFrom, 0).ToString("yyyy-MM-dd HH:mm:ss");
I get something like this:
2018-01-19 13:11:00
When the initial date that I tried to parse was this:
"20/10/2018"
The hours and minutes are correct. But the day and month are not.
I think the output is because the time on my computer is something like this:
11-Oct-18. This may be a cultural problem.
How can I get the correct date from what is expected?

Converting time to Universal Time making the result differ. Try "dd/MM/yyyy" as parse string. "mm" is used for minutes in datetime parsing refer this documentation for datetime custom formats Custom Date and Time Format Strings
Ex -
DateTime datefrom = DateTime.ParseExact("20/10/2018","dd/MM/yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(datefrom); //20.10.2018 00:00:00 without universal time
DateTime datefromUniversal = DateTime.ParseExact("20/10/2018","dd/MM/yyyy", CultureInfo.InvariantCulture).ToUniversalTime();
Console.WriteLine(datefromUniversal); //19.10.2018 22:00:00 with universal time
int hoursFrom = "13"!=String.Empty?Convert.ToInt32("13"):0;
int minutesFrom = "11" != String.Empty ? Convert.ToInt32("11") : 0;
var date1 = new DateTime(datefrom.Year, datefrom.Month, datefrom.Day, hoursFrom, minutesFrom, 0).ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine(date1);
Hope now you understood

Related

Convert date and time into Correct format to compare to current date

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

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'

How to convert dd/mm to Mysql Datetime format in c#

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

Error: No overload for method "ToString" takes 1 arguments

I am trying to format date in a specific order
Time = DateTime.Parse(p.Time.ToString("dd-MM-yyyy HH:mm:ss"))
Data type of Time is DateTime
But i am getting this error:
No overload for method "ToString" takes 1 arguments.
p is the object of the table from which i am getting Time.
List<ProductImageMapWrapper> lstpm = new List<ProductImageMapWrapper>();
lstpm = _db.ProductImageMaps.Where(i => i.ClientId == null && i.BrandId == null).Select(p => new ProductImageMapWrapper
{
Time= // Problem here
}
Now, I tried using it this way
Time = DateTime.Parse(string.Format("{dd-MM-yyyy HH:mm:ss}", p.Time))
but then i got this error:
LINQ to Entities does not recognize the method System.DateTime Parse(System.String) method, and this method cannot be translated into a store expression.
String Time = Convert.ToDateTime(p.Time).ToString("dd-MM-yyyy HH:mm:ss");
It looks to me like the Time property of both types (ProductImageMap and ProductImageMapWrapper) is a DateTime. If that is true, then you should use Time = p.Time
There's a common misconception that a DateTime value somehow has a format. Actually, you apply a given format when you convert the DateTime value into a string. To copy a DateTime value from one place to another, just assign it.
parenthesis are in the wrong place. You cannot parse it as that format. You have to parse P, then format as the string.
DateTime.Parse(System.DateTime.Now).ToString("dd-MM-yyyy HH:mm:ss")
Here is the example how to parse date from string and you can correct this for your structure to work:
string p = "21-11-2013 11:12:13";
DateTime time = DateTime.ParseExact(p, "dd-MM-yyyy HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
Considering p.Time as string value in the date format you suggested, I think you want to parse string to DateTime as,
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "dd-MM-yyyy HH:mm:ss"; //This should be format that you get in string
List<ProductImageMapWrapper> lstpm = new List<ProductImageMapWrapper>();
lstpm = _db.ProductImageMaps.Where(i => i.ClientId == null && i.BrandId == null).Select(p => new ProductImageMapWrapper
{
Time = DateTime.ParseExact(p.Time, format, provider)
});
Might Help
var selectQuery=from add in db.address
select add.myDate.toString("{0:dddd, MMMM d, yyyy}");
selectQuery.Distinct();
Normal Convers.
DateTime time = DateTime.Now; // Use current time
string format = "MMM ddd d HH:mm yyyy"; // Use this format
Console.WriteLine(time.ToString(format));
1.MMM display three-letter month
2.ddd display three-letter day of the WEEK
3.d display day of the MONTH
4.HH display two-digit hours on 24-hour scale
5.mm display two-digit minutes
6.yyyy displayfour-digit year
You want to use DateTime.ToString(format) not Nullable.ToString(no
overload):
DateTime? myDate = form.dteStartDate;
string sqlFormattedDate = myDate.Value.ToString("yyyy-MM-dd HH:mm:ss");
Of course this doesn't handle the case that there is no value. Perhaps something like this:
string sqlFormattedDate = myDate.HasValue
? myDate.Value.ToString("yyyy-MM-dd HH:mm:ss")
: "<not available>";

C# Getting Just Date From Timestamp

If I have a timestamp in the form: yyyy-mm-dd hh:mm:ss:mmm
How can I just extract the date from the timestamp?
For instance, if a timestamp reads: "2010-05-18 08:36:52:236" what is the best way to just get 2010-05-18 from it.
What I'm trying to do is isolate the date portion of the timestamp, define a custom time for it to create a new time stamp. Is there a more efficient way to define the time of the timestamp without first taking out the date, and then adding a new time?
DateTime.Parse("2010-05-18 08:36:52:236").ToString("yyyy-MM-dd");
You should use the DateTime type:
DateTime original = DateTime.Parse(str);
DateTime modified = original.Date + new TimeSpan(13, 15, 00);
string str = modified.ToString("yyyy-MM-dd HH:mm:ss:fff");
Your format is non-standard, so you'll need to call ParseExact instead of Parse:
DateTime original = DateTime.ParseExact(str, "yyyy-MM-dd HH:mm:ss:fff", CultureInfo.InvariantCulture);
You could use substring:
"2010-05-18 08:36:52:236".Substring(0, 10);
Or use ParseExact:
DateTime.ParseExact("2010-05-18 08:36:52:236",
"yyyy-MM-dd HH:mm:ss:fff",
CultureInfo.InvariantCulture)
.ToString("yyyy-MM-dd");
DateTime date;
if (DateTime.TryParse(dateString, out date))
{
date = date.Date; // Get's the date-only component.
// Do something cool.
}
else
{
// Flip out because you didn't get a real date.
}
Get the .Date member on the DateTime
DateTime date = DateTime.Now;
DateTime midnightDate = date.Date;
use it like this:
var x = DateTime.Now.Date; //will give you midnight today
x.AddDays(1).AddTicks(-1); //use these method calls to modify the date to whats needed.
The best (and fastest) way to do this is to convert the date to an integer as the time part is stored in the decimal part.
Try this:
select convert(datetime,convert(int, #yourdate))
So you convert it to an integer and then back to a data and voila, time part is gone.
Of course subtracting this result from the original value will give you the time part only.

Categories

Resources