[SalesForce] Convert String to Time format Apex

1) I have a lighting input of time.

2) I use JS to get the value of this field.

component.find("timeChange1").get("v.value")

3) I want to call an apex class to update the time when this JS function is run.

4) However, the format I send the time in, is string due to JS.

Question) Is it possible to convert a string to a "time" only format not date time. If so how?

<lightning:input type="time" name="time1" aura:id="timeChange1" label="Preferred first chasing Time" value= "{!v.firstTime}"/>

5) Value of variable being passed to apex '18:00'

6) Apex Class

    public static void updateTime(String recordId, time timeChange){
      Lead obj = new Lead();
      obj = [select Monday__c, Tuesday__c,  Wednesday__c, Thursday__c, Friday__c, Saturday__c, First_Chasing_Time__c, Second_Chasing_Time__c FROM Lead WHERE Id = : recordId LIMIT 1]; 
      obj.First_Chasing_Time__c = timeChange;
      update obj;

Best Answer

If the time is always going to be in the format of 'HH:mm' you can convert the String '16:00' to a Time like this:

public static void updateTime(String recordId, String strTimeChange){

  String[] strTimeSplit = strTimeChange.split(':');
  Time timeChange = Time.newInstance( Integer.valueOf(strTimeSplit[0]) //hour
                                     ,Integer.valueOf(strTimeSplit[1]) //min
                                     ,0                                //sec
                                     ,0);                              //ms
obj.First_Chasing_Time__c = timeChange;
update obj;

You should probably add some error handling to your use case.

If you can handle the timechange in JS and pass a formatted string to your apex class there are several datetime methods that are easier to use.

for example: DateTime.parse(String);