skip to Main Content

This is what I have:

  startDate: DateTime.parse(dateEvent.split(' ').reversed.join()),
  endDate: DateTime.parse(dateEvent.split(' ').reversed.join()),

dateEvent gives me the date selected in the format yyyyMMdd from the format dd MM yyyy.

I need to add the time to this in order to add it to the calendar. I receive this as timeHour and timeMinute which are individual numbers. example: 8:30am would come as 8 and 30, 8:30pm would come as 16 and 30.

The ideal result would be yyyyMMdd HH:mm:00

2

Answers


  1. Chosen as BEST ANSWER

    So the answer given was close, but the result was much simpler. I needed to add the line:

    DateFormat dateFormat = DateFormat("dd-MM-yyyy HH:mm:ss");
    

    Then I could write my dates as a dateFormat which resulted in a simpler outcome as it could all be tied together in a String recognisable by the Calander apps:

      startDate: dateFormat.parse("$dateEvent $timeHour:$timeMinute:00"),
      endDate: dateFormat.parse("$dateEvent $timeHour:$timeMinute:00"),
    

  2. import 'package:intl/intl.dart';
    
    DateTime _getDateTime(String date, int timeHour, int timeMinute) {
      final dateTime = DateTime.parse(date);
      final hour = timeHour == 12 ? 0 : timeHour;
      final minute = timeMinute;
      final time = TimeOfDay(hour: hour, minute: minute);
      return dateTime.add(time);
    }
    
    String _formatDateTime(DateTime dateTime) {
      final dateFormat = DateFormat('yyyyMMdd HH:mm:00');
      return dateFormat.format(dateTime);
    }
    
    void main() {
      final date = '20230727';
      final timeHour = 8;
      final timeMinute = 30;
      final dateTime = _getDateTime(date, timeHour, timeMinute);
      final formattedDateTime = _formatDateTime(dateTime);
      print(formattedDateTime); // 20230727 08:30:00
    }
    

    This code will first parse the date string into a DateTime object. Then, it will create a TimeOfDay object with the specified hour and minute. Finally, it will add the time to the date and format the resulting DateTime object in the yyyyMMdd HH:mm:00 format.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search