C/C++ : datenum code

Matlab have a function to convert string of date to double number. This double number represent preset day from (January 0, 0000). This function name is “datenum”. I want to use this function in C/C++.  I have research this function and create a simple code how to use datenum in our C/C++ code (convert datenum to C/C++) . Please check the full code below :

#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <stdio.h>
using namespace std;

static int cumdays[] = {0, 0,31,59,90,120,151,181,212,243,273,304,334};
double datenum(int year, int mon, int day, int hour, int imin, int sec, int mil)
{
	int tmp1, tmp2, tmp3;
	double	tmp4, tmp5;
	double dNum;

	/* Calculate the serial date number:*/
	tmp1 = 365 * year  + cumdays[mon] + day;
	tmp2 = year / 4 - year / 100 + year / 400;
	tmp3 = (year % 4 != 0) - (year % 100 != 0) + (year % 400 != 0);
	tmp4 = (double) (tmp1+tmp2+tmp3);
	tmp5 = (hour * 3600000 + imin * 60000 + sec * 1000 + mil) / 86400000.0;

	dNum = tmp4 + tmp5;

	if (mon > 2) {
		if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
			dNum += 1.0;
		}
	}

	return(dNum);
}

int main(int argc, char **argv)
{
	double currT;
	currT = datenum(2014, 12, 29, 12, 45, 20, 123);
	cout.precision(15);
	cout<<"TIME = "<< currT << endl;
	return(0);
}

Compile this program using command :

g++ demo_datenum.cpp -o demo_datenum

Running the program :

toto@ubuntu:~/Documents$ ./demo_datenum 
TIME = 735962.531482905

If you check using Matlab, this output have same result.

Add a Comment

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.