a-marenkov / gsheets

A Dart library for working with Google Sheets API.
Other
78 stars 31 forks source link

Is there any equivalent of getDisplayValues() here? #64

Closed alX-u closed 1 year ago

alX-u commented 2 years ago

The thing is I'm saving dates in my spreadsheet, and when I perform the worksheet.values.map.lastRow() to get the last added row info, I obtain the date with a wrong format. I want it as a string, but given that Gsheets views it as a date/number. If the date is 2021/12/22, for example, I obtain something like 445040 when reading it with lastRow(). Is there a way to obtain the value as a string? Thanks.

a-marenkov commented 2 years ago

Hi @alX-u

ValueRenderOption might help you, but i would recommend you instead of reading date as a raw string, parsing timestamp value into DateTime.

Try using these two methods:

const gsDateBase = 2209161600 / 86400;
const gsDateFactor = 86400000;

double dateToGsheets(DateTime dateTime, {bool localTime = true}) {
  final offset = dateTime.millisecondsSinceEpoch / gsDateFactor;
  final shift = localTime ? dateTime.timeZoneOffset.inHours / 24 : 0;
  return gsDateBase + offset + shift;
}

DateTime? dateFromGsheets(String value, {bool localTime = true}) {
  final date = double.tryParse(value);
  if (date == null) return null;
  final millis = (date - gsDateBase) * gsDateFactor;
  return DateTime.fromMillisecondsSinceEpoch(millis.round(), isUtc: localTime);
}
alX-u commented 2 years ago

Hi @alX-u

ValueRenderOption might help you, but i would recommend you instead of reading date as a raw string, parsing timestamp value into DateTime.

Try using these two methods:

const gsDateBase = 2209161600 / 86400;
const gsDateFactor = 86400000;

double dateToGsheets(DateTime dateTime, {bool localTime = true}) {
  final offset = dateTime.millisecondsSinceEpoch / gsDateFactor;
  final shift = localTime ? dateTime.timeZoneOffset.inHours / 24 : 0;
  return gsDateBase + offset + shift;
}

DateTime? dateFromGsheets(String value, {bool localTime = true}) {
  final date = double.tryParse(value);
  if (date == null) return null;
  final millis = (date - gsDateBase) * gsDateFactor;
  return DateTime.fromMillisecondsSinceEpoch(millis.round(), isUtc: localTime);
}

Yes, this works amazingly, thanks a lot!