user5462062
user5462062

Reputation:

Rewrite date function from C++ to C#

I have a C++ function like

string LocalDate()
{
  time_t current = time(NULL);
  struct tm *local_time = localtime(&current);
  char TIME[0xFF] ;
  sprintf(TIME, "%02d%02d%02d%02d%02d%02d", local_time->tm_year % 100, local_time->tm_mon + 1,
  local_time->tm_mday, local_time->tm_hour, local_time->tm_min, local_time->tm_sec);
  return string(TIME);
}

Which I rewrote to C# like this

public static string LocalDate()
{
    DateTime value = DateTime.Now;
    return String.Format("{0}{1}{2}{3}{4}{5}", value.Year.ToString("00"),
                                               value.Month.ToString("00"), value.Day.ToString("00"),
                                               value.Hour.ToString("00"), value.Minute.ToString("00"), value.Second.ToString("00"));
}

The only different being C# returns 20151029155030. While C++ returns 151029155030. (Year part in C++ has value 115 actually - the structure I mean)

You can see C++ omits 20 of the year part. My first question is doesn't C++ part seem weird to you? How will it correctly calculate years say in 2212? (Will not it be same as 2112? etc.)

How to make C# output same value do %100?

Upvotes: 1

Views: 205

Answers (2)

3dz9j56
3dz9j56

Reputation: 112

(Year part in C++ has value 115 actually - the structure I mean)

You can see C++ omits 20 of the year part. My first question is doesn't C++ part seem weird to you? How will it correctly calculate years say in 2212? (Will not it be same as 2112? etc.

DateTime has as year value the years since 0. https://msdn.microsoft.com/en-us/library/system.datetime.year%28v=vs.110%29.aspx

Upvotes: 0

juharr
juharr

Reputation: 32266

You can just use a Custom DateTime format instead

return DateTime.Now.ToString("yyMMddHHmmss");

The problem with your implementation is that value.Year.ToString("00") does not limit the string to two digits. That only makes sure that the string will have at least 2 digits and left pad with zeros if there are less. To replicate the C++ could you could have done value.Year % 100 instead.

Upvotes: 2

Related Questions