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'
Related
I have a string which contains a date as shown below
string dateTime = "18-Aug-2016 12:02:44 AM PDT";
I want it to be converted to the below format
Output = 2016-08-18T00:02:44-07:00
I tried the below code, but still I need to modify it to get my required output
string mydate = dateTime.Replace("PDT", "-0700");
DateTime dt = Convert.ToDateTime(mydate);
string dateTime = "18-Aug-2016 12:02:44 AM PDT";
string mydate = dateTime.Replace("PDT", "-0700");
DateTime dt = Convert.ToDateTime(mydate);
Console.WriteLine("The current date and time: {0:O}", dt);
Gives me the following output:
The current date and time: 2016-08-18T09:02:44.0000000+02:00
Not sure if PDT is globally unique, nor if that zone changes during daylight savings time.
Id report back to the Google server team that they are returning something "interesting"
I want to get the last seen of user and save it to my sql database in mvc5 . I got the last seen in controller with code like this:
users.userlast=DateTime.Now;
and saved to my database in this format "2015-08-06 12:12:13.443". I want to get datetime only format day,month,year, hour and minute.
I can't use something like this,
var dateTime = DateTime.ParseExact("12/02/21 10:56:09", "yy/MM/dd HH:mm", CultureInfo.InvariantCulture);
var text = dateTime.ToString("MMM. dd, yyyy HH:mm");
It did not work because my last seen column is a datetime type not string. What should i do?
Thanks.
Edit:
Like whatsup App., i want to see only hour and minute, not seconds as last seen.
You say that you are storing as a datetime type, in which case the you shouldn't need to convert a string to a DateTime. In fact you shouldn't need to do any parsing.
When you query the database you should get a DateTime, on which you can call the ToString() you want.
to get datetime in format day, month, year, hour and minute only (without seconds, milliseconds), create a new DateTime value before save:
var dt = DateTime.Now;
users.userlast = dt.Date.AddHours(dt.Hour).AddMinutes(dt.Minute);
You don't have to worry about the format you save in the database. When you want to represent it in your specific format you can ToString it accordingly.
I want to get datetime only format day,month,year, hour and minute.
string text = dateTime.ToString("yyyy-MM-dd HH:mm",
CultureInfo.InvariantCulture);
CultureInfo.InvariantCulture is to use your specified culture regardless of the user's current culture.
You can use InvariantCulture because your user must be in a culture that uses a dot instead of a colon:
DateTime.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
Just do like that
var formattedDateTime = yourLastSeenDateTime.ToString("MMM. dd, yyyy HH:mm", CultureInfo.InvariantCulture);
EDIT: Try this as you mentioned in comments
DateTime dbDate = yourLastSeenDateTime;
DateTime newDateTime = new DateTime(dbDate.Year, dbDate.Month, dbDate.Day, dbDate.Hour, dbDate.Minute, 0);
i want to calculate a checktime to the time now and get the hours.
I have a string "time" for example...
Jun 06 2013 07:23:06
and with DateTime.Now I get the Time now. The Problem is now that i can't calculate the difference :(
I need them in my Project where I get from the License Server the time from a user and I want to show the difference to now. I want show this in hours.
You can use the Parse method of the DateTIme class to parse a string as a date and the subtract that from now.
TimeSpan diff = DateTime.Now - DateTime.Parse(dateString);
var hours = diff.Hours
The above exsmple of course requires the date to be in a specific format. You can if needed use DateTIme.ParseExact and specify a specific format yourself
You need to first convert your string to DateTime. here you have custom format so you can use DateTime.ParseExact or DateTime.TryParseExact method as below
DateTime dt;
if (DateTime.TryParseExact("Jun 06 2013 07:23:06", "MMM dd yyyy HH:mm:ss", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// get difference
var inDays = (DateTime.Now - dt).Days;
}
You can use TimeSpan.Hours property like;
Gets the hours component of the time interval represented by the
current TimeSpan structure.
string dateString = "Jun 06 2013 07:23:06";
var differenceHours = (DateTime.Now - DateTime.Parse(dateString)).Hours;
Console.WriteLine(differenceHours);
Here a DEMO.
If you want to convert your custom formatted string to DateTime, you can use DateTime.ParseExact which need exact format matching between string and datetime.
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
u may try it
DataTime diff = DateTime.Now - Convert.ToDataTime(dateString);
var hours = diff.Hours
assume I have this string :
How can I convert it to DateTimeOffset object that will have UTC time - means -00:00 as Time Zone - even if I run it on machine on a specific timezone?
Assume String:
"2012-10-08T04:50:12.0000000"
Convert.ToDateTime("2012-10-08T04:50:12.0000000" + "Z");
--> DateTime d = {10/8/2012 6:50:12 AM}
and I want it to be
DateTime d = {10/8/2012 4:50:12 AM}
as if it will understand I want the date as simple as it comes (BTW - my machine is in timezone +02:00)
Use DateTimeOffset.Parse(string).UtcDateTime.
The accepted answer did not work for me. Using DateTimeOffset.Parse(string) or DateTimeOffset.ParseExact(string) with the .UtcDateTime converter correctly changed the kind of the DateTime to UTC, but also converted the time.
To get to a DateTime that has the same time as the original string time, but in UTC use the following:
DateTime dt = DateTime.ParseExact(string, "yyyy-MM-ddTHH:mm:ss.fffffff",
CultureInfo.InvariantCulture);
dt = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
I did this by checking the DateTimeKind. On my function, 2 different types of date-times are coming. What I want is to convert UTC time to local time from the below function. Input parameter date is always coming as UTC.
Eg inputs: 2021-01-19 07:43:00 AM and 01/07/2021 02:16:00 PM +00:00
public static DateTime GetDateTime(string date)
{
try
{
DateTime parsedDate = DateTime.Parse(date, GetCulture()); //invarient culture
if (parsedDate.Kind == DateTimeKind.Unspecified)
{
parsedDate = DateTime.SpecifyKind(parsedDate, DateTimeKind.Utc);
}
return parsedDate.ToLocalTime();
}
catch (Exception e)
{
throw;
}
}
var universalDateTime = DateTime.Parse(your_date_time_string).ToUniversalTime();
Using, DateTimeStyles.AssumeUniversal in DateTime.Parse(...) will do the job,
Ex:
DateTime.Parse("2023-01-02 9:26", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal)
then the parsed datetime will be in UTC
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.