Skip to content

Commit

Permalink
fix ycphs#288
Browse files Browse the repository at this point in the history
  • Loading branch information
JanMarvin committed Nov 8, 2021
1 parent f8bbdd0 commit 45d7fdc
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
Binary file added inst/extdata/gh_issue_288.xlsx
Binary file not shown.
16 changes: 11 additions & 5 deletions src/write_file.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@

#include "openxlsx.h"
#include <regex>


//' @import Rcpp
Expand Down Expand Up @@ -225,16 +226,21 @@ SEXP buildMatrixMixed(CharacterVector v,
if(!notNAElements[ri]){
datetmp[ri] = NA_REAL; //IF TRUE, TRUE else FALSE
}else{
// dt_str = as<std::string>(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<Rcpp::Date>(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<std::string>(m(ri,i)));
}
}

Expand Down
18 changes: 18 additions & 0 deletions tests/testthat/test-date_time_conversion.R
Original file line number Diff line number Diff line change
Expand Up @@ -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)

})

0 comments on commit 45d7fdc

Please sign in to comment.