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.
Related
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'
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 have various strings of type: 7/12/2012 12:02:39 AM
and would like to convert them all to just 7/12/2012 12:00:00 AM
Basically the date needs be the same, just the time must be set to 12:00:00 AM for all.
What is the best way to approach that? Except just looking for " " and replacing with 12:00:00 AM
First, parse them to a DateTime. Then you can use the Date property(0h) and parse it back to a String by using DateTime.ToString:
var oldDate = DateTime.Parse("7/12/2012 12:02:39 AM");
var usCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
var newDateStr = oldDate.Date.ToString( usCulture );
Custom Date and Time Format Strings
only just noticed that 12 AM is midnight not highnoon
You can create new DateTime instance via constuctor:
var newDate = new DateTime(oldDate.Year, oldDate.Month, oldDate.Day, 12, 0, 0);
or by adding 12 hours to the date part of the DateTime(0h):
var newDate = oldDate.Date.AddHours(12);
Parse them as DateTime
Write them back to string using yourDateTime.Date.ToString(#"G", CultureInfo.CreateSpecificCulture("en-us"))
use DateTime.Parse and specify the CulterInfo
DateTime mydat = DateTime.Parse(myString, CultureInfo.InvariantCulture);
I am retrieving data from an iSeries where there is a separate date and time fields. I want to join them into a DateTime field in my C# project. I don't see a way to add just a time to a DateTime field. How would you suggest accomplishing this?
You can do this quite easily:
DateTime dateOnly;
DateTime timeOnly;
...
DateTime combined = dateOnly.Date.Add(timeOnly.TimeOfDay);
TimeOfDay returns a TimeSpan, which you then add to the date.
Edit (thanks to commenters below) - to be safe, use dateOnly.Date to ensure the date part only.
How are they being stored? Assuming that the date portion is being stored as a DateTime of midnight of the day in question and the time is a TimeSpan, you can just add them.
DateTime date = ...;
TimeSpan time = ...;
DateTime result = date + time;
You could easily construct a TimeSpan from your "time" field.
Once you have that, just do:
TimeSpan time = GetTimeFieldData();
dateField = dateField.Add(time);
Datetime date = new DateTime(Date1.Year, Date1.Month, Date1.Day, Time1.Hour, Time1.Minute, Time1.Second);
You can add a TimeSpan to a DateTime and write something like this.
// inside consuming function
ISeriesObject obj = getMyObject();
DateTime dt = getDate(obj) + getTime(obj);
private DateTime getDate(ISeriesObject obj)
{
//return a DateTime
}
private TimeSpan getTime(ISeriesObject obj)
{
//return a TimeSpan
}
My answer addresses joining two objects of DateOnly and TimeOnly in .NET 6:
DateOnly orderDate = ...
TimeOnly orderTime = ...
DateTime orderDateTime = orderDate.ToDateTime(orderTime);
This should do:
var output = date.Date + time.TimeOfDay;
or
var output = new DateTime(date.Year, date.Month, date.Day,
time.Hour, time.Minute, time.Second);
suppose that both variable date and time are both of Type DateTime
Note that adding the time to the date is not your biggest problem here. As #Reed Copsey mentioned, you just create a DateTime from the date and then .Add the time.
However, you need to make sure that the iSeries date and time (a Unix time most probably) are in the same representation as the .Net representation. Thus, you most probably need to convert it by adding it to a Jan 1, 1970 DateTime as well.
Cant you simply format the date part and time part as separate strings, then join them together? Then you can parse the string back to a DateTime object
I use this to convert DateTime value into Date and then I add 00:00:00 and 23:59:59 to make sure whole day is taken into consideration when counting stuff. I'm pretty sure it's wrong way of doing things. What would be the right way?
DateTime varObliczOd = DateTime.Parse(dateTimeWycenaPortfelaObliczDataOd.Value.ToShortDateString() + " 00:00:00");
DateTime varObliczDo = DateTime.Parse(dateTimeWycenaPortfelaObliczDataDo.Value.ToShortDateString() + " 23:59:59");
if dateTimeWycenaPortfelaObliczDataOd is of type DateTime, You can use:
dateTimeWycenaPortfelaObliczDataOd.Date
to get the date part only (time will be 00:00:00...).
If you want to get the very last tick of the date, you can use:
dateTimeWycenaPortfelaObliczDataOd.Date.AddDays(1).AddTicks(-1)
but you really better work with the next date (.AddDays(1)).
In any case, there is no need to convert to string and back to DateTime.
DateTime objects have a Date property which might be what you need.
You can use the following properties / methods on a DateTime object to get your values :
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.Date;
DateTime varObliczDo = dateTimeWycenaPortfelaObliczDataOd.AddDayes(1).AddTicks(-1);
It would help to know why you're needing it, but this would work.
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.Date;
DateTime varObliczDo = varObliczOd.AddDays(1).AddSeconds(-1);
Using the Date attribute and then manipulating them directly to create the required time component - no need to bother with parsing and conversion.
You could use the Date property of the DateTime object to accomplish what you need.
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.Value.Date;
DateTime varObliczDo = dateTimeWycenaPortfelaObliczDataDo.Value.Date.AddDays(1);
If you really want it to end at 23:59:59 you can do:
DateTime varObliczDo = dateTimeWycenaPortfelaObliczDataDo.Value.Date.AddDays(1).AddSeconds(-1);
Will set varObliczDo to be your ending date with no time plus one day (at midnight). So if dateTimeWycenaPortfelaObliczDataDo was 2010-03-05 16:12:12 it would now be 2010-03-06 00:00:00.
Something like this maybe? I've typed this out of my head, there are probably some mistakes in the code.
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.AddSeconds(-dateTimeWycenaPortfelaObliczDataOd.Seconds).AddMinutes(-dateTimeWycenaPortfelaObliczDataOd.Minutes).AddHours(-dateTimeWycenaPortfelaObliczDataOd.Hours);
DateTime varObliczDo = new DateTime(dateTimeWycenaPortfelaObliczDataDo.Year, dateTimeWycenaPortfelaObliczDataDo.Month, dateTimeWycenaPortfelaObliczDataDoDay, 23, 59, 59);
DateTime newDate = new DateTime( oldDate.Year, oldDate.Month, oldDate.Day, 23, 59,59 )
DateTime newDate = new DateTime( oldDate.Year, oldDate.Month, oldDate.Day, 0, 0, 0 )
You could work with TimeSpan:
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd - new TimeSpan(dateTimeWycenaPortfelaObliczDataOd.Hours, dateTimeWycenaPortfelaObliczDataOd.Minutes, dateTimeWycenaPortfelaObliczDataOd.Seconds);
Like that you avoid at least the parsing, which can fail depending on the local culture settings.