Question

I'm using the MPXJ library in .NET for parsing MS Project (MPP) files, and it's working great. The one issue I'm having is trying to translate the task Start and Finish date into .NET DateTime to use with my data models.

I am going through all the tasks and calling task.getFinish() and task.getStart() that both return javva.util.Date objects.

When I use task.getFinish().getYear(), task.getFinish().getMonth(), etc. to build up a new DateTime object it warns me that they are obsolete.

What is the best way to get the start and finish dates from MPXJ into a .NET DateTime object?

Thanks.

Was it helpful?

Solution

I am also using MPXJ and had the same issue. There are a couple of ways to deal with this. I'll outline two ways below (I have used both and am not sure which is better):

Dim cal As New GregorianCalendar()
cal.setTime(task.getStart())

'have to add one to month value because it is 0 - 11
Dim startDate as New Date(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND))

This is the way that they want you to do it when they say that .getYear is obsolete.

The other way I've done it is to convert the Java date to a string and then use Date.Parse to get it into a .NET Date variable. I use a nullable type because the Java Date could be null.

Dim d as java.util.Date = t.getStart()
Dim startDate As New Nullable(Of Date)

If d IsNot Nothing Then
    Dim dateString As String = New java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(d)

    startDate  = Date.Parse(dateString)
End If

You can use a different date format string if you don't need all the parts, or if you want to include timezone info. Here's a list of the format string choices for Java.

Update

Another, perhaps more performant way of doing this (than string parsing) is the following:

Dim startDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(d.getTime()).ToLocalTime();

OTHER TIPS

I know I'm over two years late on this one, but in case it's useful to you or anyone else reading this thread, here's a simple little extension method I threw together (in C#) to handle this conversion:

internal static DateTime ToDateTime(this java.util.Date javaDate)
{
    var cal = java.util.Calendar.getInstance();
    cal.setTime(javaDate);

    // note that the Month component of java.util.Date  
    // from 0-11 (i.e. Jan == 0)
    return new DateTime(cal.get(java.util.Calendar.YEAR),
                        cal.get(java.util.Calendar.MONTH) + 1,
                        cal.get(java.util.Calendar.DAY_OF_MONTH),
                        cal.get(java.util.Calendar.HOUR_OF_DAY),
                        cal.get(java.util.Calendar.MINUTE),
                        cal.get(java.util.Calendar.SECOND));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top