Ionic react datetime showing incorrect time when editing

I am new to Ionic React. I am trying to make a calendar app in which I can add/edit/delete Tasks. I can do all of that, but heres the issue.

When I edit the startDate or endDate the time seems to be 2 hours in the past. So when I create a startDate: 7-4-2024 13:00 and endDate 9-4-2024 23:59 and click edit, the new values inside the edit-mode change to: startDate 7-4-2024 11:00 and for endDate 9-4-2024 21:59. Here comes the weird part of it. When I click save (or check the console.log(newTask) the time seems to be saved correct. For example when I edit a Task en change the time to eg. 17:00, the time spinner automaticly jumps to 15:00. But when I save the task the time is saved at 17:00.

TLDR, the datetime only shows incorrect when I try to edit a Task, but after saving they do show the correct time.

Anyone have any idea on how to fix this? If anyone knows a better approach to doing this, ANY help is welcome :)!

EventComponentList.tsx:

export interface TaskComponentProps {
    task: Task;
    index: number;
    onDelete: () => void;
    onEdit: (newTask: Task) => void;
}

const TaskComponent: React.FC<TaskComponentProps> = ({task, onDelete, onEdit}) => {

    const {
        handleInputChange,
        handleDateChange,
        newTask,
        expandedText,
        setExpandedText,
        editing,
        setEditing,
        setNewTask,
        handleToggleChange,
    } = useTaskForm();

    // useEffect hook to reset newTask when editing mode is turned off
    useEffect(() => {
        if (!editing) {
            setNewTask({...task}); // Reset newTask when editing mode is turned off
        }
    }, [editing, task]);

    const handleEditClick = () => {
        const start = new Date(newTask.startDate)
        const end = new Date(newTask.endDate)

        let x = (new Date()).getTimezoneOffset() * 60000;
        let localISOTimeStart = (new Date(start.getTime() - x)).toISOString();
        let localISOTimeEnd = (new Date(end.getTime() - x)).toISOString();

        console.log('start', start);
        console.log('end', end);
        setNewTask({ // Aanpassen naar directe instelling van het nieuwe Task object
            ...newTask,
            startDate: localISOTimeStart,
            endDate: localISOTimeEnd
        });

        setEditing(true);
    };

    const handleSaveClick = () => {
        onEdit(newTask); // Zorg ervoor dat de bewerkte taak correct wordt doorgegeven
        setEditing(false); // Turn off editing mode
    };

    const handleCancelClick = () => {
        setEditing(false); // Turn off editing mode
    };

    const toggleExpand = (textType: string) => {
        setExpandedText(expandedText === textType ? null : textType); // Toggle expanded text
    };

     return (
        <IonCard>
           
                <IonList className={'edit-task-form'}>
                    <IonItem>
                      <IonTextarea
                            label={"Name"}
                            labelPlacement={"floating"}
                            autoGrow={true}
                            name="name"
                            value={newTask.title}
                            onIonChange={(e) => setNewTask({...newTask, title: e.detail.value!})}
                        />
                    </IonItem>

                    {/* rest of the inputs */}

                    <IonItem>
                        <IonLabel>Startdatum</IonLabel>
                        <IonDatetimeButton datetime="startDate"></IonDatetimeButton>
                        <IonModal keepContentsMounted={true}>
                            <IonDatetime
                                id="startDate"
                                onIonChange={handleDateChange('startDate')}
                                value={newTask.startDate}
                            />
                        </IonModal>
                    </IonItem>
                    <IonItem>
                        <IonLabel>Einddatum</IonLabel>
                        <IonDatetimeButton datetime={"endDate"}></IonDatetimeButton>
                        <IonModal keepContentsMounted={true}>
                            <IonDatetime
                                id="endDate"
                                onIonChange={handleDateChange('endDate')}
                                value={newTask.endDate}
                            />
                        </IonModal>
                    </IonItem>

TaskHelper.tsx:

export function useTaskForm() {

    const handleDateChange = (name: string) => (e: CustomEvent<any>) => {
        const value = new Date(e.detail.value);
        console.log('Nieuwe tijd:', value); // Controleren of de nieuwe tijd correct is
        setNewTask(prevState => ({
            ...prevState,
            [name]: value
        }));
    };

    const handleEditTask = async (index: number, editedTask: Task) => {
        const updatedTasks = [...tasks];
        updatedTasks[index] = editedTask;
        setTasks(updatedTasks);
        await (await initializeStorage).set('tasks', updatedTasks);
        setNewTask(emptyTask);
        setSelectedTaskIndex(null);
    };

    const handleSaveTask = async () => {
        const updatedTask: Task = {
            ...newTask,
        };
        const updatedTasks = [...tasks, updatedTask];
        setTasks(updatedTasks);
        await (await initializeStorage).set('tasks', updatedTasks);
        setNewTask(emptyTask);
        const now = new Date();
        const twoHoursLater = new Date(now.getTime() + 2 * 60 * 60 * 1000); // +2 uur
        document.getElementById('startDate')?.setAttribute('value', twoHoursLater.toISOString());
        document.getElementById('endDate')?.setAttribute('value', twoHoursLater.toISOString());
        dismiss(); 
    };

Task.tsx:


interface Task {
  title: string;
  description: string;
  startDate: Date;
  endDate: Date;
  openTimeSlot: boolean;
  remindMe: boolean;
  priority: number;
  category: number;
  url: string;
  note: string;
}

export default Task; 

things I’ve tried:

value={newTask.startDate ? newTask.startDate.toISOString() : undefined} display-timezone="UTC"

value={newTask.startDate ? newTask.startDate.toISOString() : undefined} // Convert Date to string onIonChange={(e) => setNewTask({...newTask, startDate: new Date(e.detail.value!)})}

value={newTask.startDate.getTime() + 2 * 60 * 60 * 1000).toISOString()}

none of the above seem to work when editing a Task :`(

1 Like

Please use proper code blocks so we can easily read your code - Extended Syntax | Markdown Guide

1 Like

Thanks for the reply, changed it

1 Like