QVariant var = QVariant("2022-03-18"); QDate date = var.toDate(); // date = QDate(2022, 3, 18)
QVariant var = QVariant("invalid date"); if (var.canConvert(QVariant::Date)) { QDate date = var.toDate(); // this will throw an exception } else { // handle the error }In this example, we create a QVariant that stores an invalid date string. We use the QVariant::canConvert() method to check if the variant can be converted to a QDate object. Since the string is not a valid date, the conversion will fail and throw an exception. We catch the exception in the calling code and handle the error accordingly. Package library: QtCore.