Creating DateTime object in Visual C++ - datetime

I am familiar with creating DateTime object based on current system time
DateTime dtObject = DateTime::Now;
My question is: if I have integer variables iHour, iMinute and iSecond, how do I "put them back" into a DateTime object?
I hope I made myself clear. Thanks in advance!

Something along the lines of
DateTime today = DateTime::Today;
DateTime todayWithTime(today.Year, today.Month, today.Day,
hour, minute, second);
Another approach:
DateTime todayWithTime = DateTime::Today + TimeSpan(hour, minute, second);

Related

Symfony add 1 day to current day

I want to get the actual time and add one day to it, setter below is datetime column type and it doesn't accept the date function. What should i do?
$password->setExpiretime(date("Y-m-d", time() + 86400));
You may use format method on an instance of DateTime class:
$tomorrow = new DateTime('tomorrow');
$password->setExpiretime($tomorrow->format('Y-m-d'));
Update
According to the comment submitted by the OP, if the return type should be DateTime Object, you may just use:
$tomorrow = new DateTime('tomorrow');
$password->setExpiretime($tomorrow);

Issue in converting Timespan variable to 12 hour format

I have a nullable variable Start time
Timespan? st=e.StartTime;//Null-able variable;
I am trying to get time in AM/PM format but I am unable to get it.
DateTime date = Convert.ToDateTime(st.ToString());
String f = String.Format("{0:hh:mm:tt}", date);
Error is:
System.FormatException: String was not recognized as a valid DateTime.
If you were to output the results of st.ToString(), you will find that it doesn't contain any date information, only hours, minutes and seconds.
This isn't a valid format for a DateTime, which generally contain date and time information.
You don't need to convert your TimeSpan to a DateTime to format it, you can just use TimeSpan.ToString():
string f = st.Value.ToString(#"hh\:mm\:tt");
For reference: http://msdn.microsoft.com/en-us/library/ee372287.aspx
Also, note the \ before the :, you must do this if you want to include literal strings in the output, as mentioned at the bottom of that documentation page.
Converting a timespan to a date is not possible, a timespan represents x amount of minutes/hours/whatever and you cannot get an exact date from that alone. If you have a date as a starting point, you can add a timespan and that will give you the new date.
st.ToString() will return "System.Nullable<Timespan>" because that is what a nullable type returns - it does not override the default Object.ToString implementation, so returns the type name.
If you want the string of the actual timespan, then you would need to do st.Value.ToString(), but you should be checking for null first (i.e. st.HasValue == true)
Edit: Also see #Sean's comment about how to output the Timespan without converting to a DateTime first.
Edit: Turns out I was slightly wrong - st.ToString() doesn't return the above. So see Sean's answer.
First convert Timespan to Datetime by adding TimeSpan to a base date of 00:00 hrs. Then on that dateTime derive the 12 hr format.
DateTime.Now.Date.Add(OpenTimeSpan).ToString(#"hh\:mm\:tt")
The Accepted Answer is wrong.
You cannot return AM/PM for a TimeSpan because it is only concerned with the length of Time,
not a Time of Day - hench the name, "TimeSpan".
Convert to a DateTime first before converting to a String:
string sTimeOfDay = new DateTime().Add(st).ToString("hh:mm tt");
Note: If your TimeSpan is nullable, then you will need to add Conditional Logic to Handle Nulls and pass in ts.Value instead of ts:
string sTimeOfDay = (st == null ? null : new DateTime().Add(st.value).ToString("hh:mm tt") );

Is there a better way to encode a (MS) DateTime as an Int?

BACKGROUND (ok to ignore/skip):
I feel like there should be a better way to do what I'm doing, but I don't know what it is and I think my solution works, but I thought I'd ask in case there is something more elegant or faster or whatever.
I am developing a web page with MS Razor MVC which uses Html.DropDownList, which gives a pick list UI control which maps choices as display strings to integer ID codes. (I don't think I can have it map strings to DateTime values.)
But in a couple of cases, I want to choose from dates that are stored as DateTime objects. I realize I could make yet another table in memory that relates ID codes to DateTime values, but I thought instead (and also because I think I may want to encode dates as ints for yet another workaround of web page annoyances), I would encode the date as an int.
PROBLEM:
How best to convert the date of a DateTime object as an int value, and then later set a DateTime's date back to that date from the encoded int. The main ugliness of my solution is that DateTime provides a read-only DayOfYear function, but no way I know of to set a date back to (Date, DayOfYear), so I wrote a method with a loop, which is cute but probably slowish.
MY CURRENT (OK) SOLUTION:
public int encodeDate(DateTime date)
{
return ((date.Year - 2012) * 400) + date.DayOfYear;
}
public DateTime decodeDateCode(int dateCode)
{
int year = (dateCode / 400) + 2012;
int day = dateCode % 400;
// MS DateTime doesn't provide a direct reverse conversion for DayOfYear, so find it:
int month = 1;
int mThresh = DateTime.DaysInMonth(year, month);
while (day > mThresh)
{
day -= mThresh;
month++;
mThresh = DateTime.DaysInMonth(year, month);
}
DateTime dateValue = new DateTime(year, month, day);
return dateValue;
}
Ho about to format the timestamp as POSIX time (POSIX time / Unix time, see http://en.wikipedia.org/wiki/Unix_time)?
I had a similar problem myself and found a great solution here: Convert a Unix timestamp to a .NET DateTime
From the link:
DateTime ConvertFromUnixTimestamp(double timestamp)
{
}
double ConvertToUnixTimestamp(DateTime date)
{
}

asp.net c# - combine / format a date and time from separate sources

I'm parsing an XML file from an external source, and I have 2 attributes which contain the date and time respectively. I'm looking for the best way to get these into a format I can parse as a date so I can do things with it, but at the moment I'm just getting errors or no results with the methods I've tried.
The date is in the format "20111215" - which is yyyymmdd as it's UK based.
The time is formatted as "1417+0000" which I presume is the time plus offset from GMT?
Basically I need to get these into UK time. I've tried using DateTime.Parse on the separate parts but both give an error as not valid format. Tried String.Format on the date part but that didn't change it at all. I presume I need to combine the 2 before parsing but I'm not sure if I need to do anything else with it to make it acceptable.
Any help appreciated.
Use a DateTimeOffset to incorporate the timezone into the DateTime.
string date = "20111215";
string time = "1417+0500";
string dateAndTime = date + time;
string format = "yyyyMMddHHmmzzz";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTimeOffset t = DateTimeOffset.ParseExact(dateAndTime, format, provider);
If you concatenate the fields together, you can then use DateTime.TryParseExact in order to parse them into a DateTime.
string input = string.Format("{0} {1}", dateString, timeString);
DateTime parsed;
if(DateTime.TryParseExact(input,
"yyyyMMdd HHmmK",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out parsed))
{
// parsed OK, use the parsed variable
}
string date = "20111215";
string time = "1417+0000";
string dateString = date + time;;
string format = "yyyyMMddHHmmK";
// or something similar, I'm not sure about the timezone
DateTime result = DateTime.ParseExact(dateString,
format,
CultureInfo.InvariantCulture);
I think this should work (i didn't test it):
string dateString = "20111215";
string timeString = "1417+0000";
int year = int.Parse(dateString.Substring(0,4));
int month = int.Parse(dateString.Substring(4,2));
int day = int.Parse(dateString.Substring(6,2));
int hour = int.Parse(dateString.Substring(0,2));
int mins = int.Parse(dateString.Substring(2,2));
DateTime d = new DateTime(year, month, day, hour, mins, 0);

How can I convert java.util.Date to org.joda.time.DateTime?

I have to use java.util.Date class as field type in a table.
But I would like to change the display format of the date field with help of joda time (confortable, prefered to use), thats why I want to convert a Date to DateTime.
I know I oversee something, because there is no such a question in stackoverflow :) but I could not find the soulution among the DateTime constructors and so on.
The reverse conversion DateTime.toDate();
exists, but what about the opposite way ?
Thanks for the answers in advance.
Cs
In Vaadin, if you want to change display format in a table without joda, you simply override the method protected String formatPropertyValue(Object rowId, Object colId,
Property property)
Here an example to do it :
Table t = new Table() {
#Override
protected String formatPropertyValue(Object rowId, Object colId,
Property property) {
Object v = property.getValue();
if (v instanceof Date) {
Date dateValue = (Date) v;
return new SimpleDateFormat("yyyy-MMMM-dd").format(dateValue);
}
return super.formatPropertyValue(rowId, colId, property);
}
};
Regards
Éric
Yes, Use Joda-Time
Definitely use Joda-Time or the java.time package in Java 8 (inspired by Joda-Time). The old java.util.Date and java.util.Calendar classes are notoriously troublesome, confusing, and outmoded.
Also, read the Wikipedia pages on UTC and ISO 8601.
Yes, Pass Date To Joda-Time Constructor
➔ Yes indeed, you can pass a java.util.Date object to the constructor of a Joda-Time DateTime object.
The API doc is a bit confusing as this apparently falls into the catch-all version of the constructor taking an java.lang.Object instance. If that Object is in fact a java.util.Date, Joda-Time will extract its millisecond-count-since-epoch and use that number as its own.
Time Zone
A DateTime constructor also assigns a time zone. By default, the JVM’s current default time zone is assigned. I recommend you always pass a desired time zone rather than rely implicitly on the default even if that means calling getDefault.
Example Code
Here is some example code in Joda-Time 2.5 showing how to pass a java.util.Date to a Joda-Time constructor.
java.util.Date date = new java.util.Date();
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTimeMontreal = new DateTime( date , zone );
DateTime dateTimeUtc = dateTimeMontreal.withZone( DateTimeZone.UTC ); // Adjust to another time zone.
Dump to console.
System.out.println( "date: " + date ); // Misleading output. A j.u.Date is in UTC but its toString method applies JVM’s current default time zone.
System.out.println( "dateTimeMontreal: " + dateTimeMontreal );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
When run.
date: Sat Oct 18 18:54:55 PDT 2014
dateTimeMontreal: 2014-10-18T21:54:55.740-04:00
dateTimeUtc: 2014-10-19T01:54:55.740Z
As shown in the Question, to go from a DateTime to java.util.Date, call toDate.
java.util.Date date = dateTimeMontreal.toDate();

Resources