a-marenkov / gsheets

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

How to parse date fields ? #80

Closed ajonno closed 1 year ago

ajonno commented 2 years ago

hi, we've got this date column in a google sheet:

2022-05-14_22-18-26

however when its read in Dart code using: await _userSheet!.values.map.allRows()

the raw object looks like this: "date" -> "44511"

how can we parse this 44511 value to get the actual date contained in the spreadsheet cell ?

rdunlocked18 commented 2 years ago

Go ahead Use this to convert both time and date!

Formated Date Will be like this 5-12-1992:

 static String? formatSheetDate(String? dateGot) {
    if (dateGot == null || dateGot == '') return null;
    final dateSome = DateTime.fromMillisecondsSinceEpoch(
        ((double.parse(dateGot) - 25569) * 86400000).toInt(),
        isUtc: true);
    var dateTime = DateTime.parse(dateSome.toString());

    var formatDate = "${dateTime.day}-${dateTime.month}-${dateTime.year}";

    return formatDate;
  }

Formated Time Will be like this 08:20 AM :

static String? formatSheetTime(String? timeGot) {
    if (timeGot == null || timeGot == '') return null;
    final dateSome = DateTime.fromMillisecondsSinceEpoch(
        ((double.parse(timeGot) - 25569) * 86400000).toInt(),
        isUtc: true);
    var dateTime = DateTime.parse(dateSome.toString());

    var formattedTime = DateFormat('hh:mm a').format(dateTime);

    return formattedTime;
  }
jeff9315 commented 2 years ago

Perfect @rdunlocked18 ... Just what I needed.