diff --git a/inst/extdata/gh_issue_288.xlsx b/inst/extdata/gh_issue_288.xlsx new file mode 100644 index 00000000..f1394610 Binary files /dev/null and b/inst/extdata/gh_issue_288.xlsx differ diff --git a/src/write_file.cpp b/src/write_file.cpp index 6df31be1..23334b0d 100644 --- a/src/write_file.cpp +++ b/src/write_file.cpp @@ -1,5 +1,6 @@ #include "openxlsx.h" +#include //' @import Rcpp @@ -225,16 +226,21 @@ SEXP buildMatrixMixed(CharacterVector v, if(!notNAElements[ri]){ datetmp[ri] = NA_REAL; //IF TRUE, TRUE else FALSE }else{ - // dt_str = as(m(ri,i)); dt_str = m(ri,i); + try{ - datetmp[ri] = Rcpp::Date(atoi(dt_str.substr(5,2).c_str()), atoi(dt_str.substr(8,2).c_str()), atoi(dt_str.substr(0,4).c_str()) ); - }catch(...) { + // Some values are incorrectly detected as dates. This regex determines if they are numerics. + // If so, they are converted to Dates. + Rcpp::Function cTD("convertToDate"); + if (std::regex_match( dt_str, std::regex( ( "((\\+|-)?[[:digit:]]+)(\\.(([[:digit:]]+)?))?" ) ) )) { + datetmp[ri] = as(cTD(dt_str)); + } else { + datetmp[ri] = Rcpp::Date(atoi(dt_str.substr(5,2).c_str()), atoi(dt_str.substr(8,2).c_str()), atoi(dt_str.substr(0,4).c_str()) ); + } + } catch(...) { Rcpp::Rcerr << "Error reading date:\n" << dt_str << "\nrow: " << ri+1 << "\ncol: " << i+1 << "\n"; throw; } - //datetmp[ri] = Date(atoi(m(ri,i)) - originAdj); - //datetmp[ri] = Date(as(m(ri,i))); } } diff --git a/tests/testthat/test-date_time_conversion.R b/tests/testthat/test-date_time_conversion.R index ab2e4e11..23307cae 100644 --- a/tests/testthat/test-date_time_conversion.R +++ b/tests/testthat/test-date_time_conversion.R @@ -33,3 +33,21 @@ test_that("convert to datetime", { x_datetime <- convertToDateTime(x, tx = "UTC") attr(x_datetime, "tzone") <- "UTC" }) + + + +test_that("read.xlsx detectDates", { + + xlsxFile <- system.file("extdata", "gh_issue_288.xlsx", package = "openxlsx") + + ref_dat <- data.frame(Date = c(as.Date(c("2021-10-20", "2021-11-03")))) + ref_num <- data.frame(Date = c(44489.4, 44503.0)) + + tst_dat <- read.xlsx(xlsxFile, detectDates = TRUE) + tst_num <- read.xlsx(xlsxFile, detectDates = FALSE) + + expect_equal(ref_dat, ref_dat) + expect_equal(ref_num, ref_num) + +}) + \ No newline at end of file