0

I just want to convert String to Time without using "newInstance()" method, it takes four integer type arguments(h,m,s,ms) , but I want this type of format "HH:MM AM/PM". I have a custom field that is "Time" type. and I'm putting value into this, but I'm facing this error. "INVALID date/time 03:15 PM"

Event__c evt = new Event__c();// this is custom object in salesforce org. 
DateTime dt = System.now();
evt.Start_Time__c = DateTime.parse(dt.format('hh:mm a')).time();

// This is Time field that i want to show on vf page as format('HH:MM AM/PM') , i'm using input type field on the VF page.

When I'm using this type of conversion it's getting an error on the VF page. "INVALID Date/Time 03:15 PM"

1
  • Any specific reason to avoid newInstance() ? Oct 23, 2019 at 10:12

2 Answers 2

0

Try this:

Event__c evt = new Event__c();// this is custom object in salesforce org. 
DateTime dt = System.now();
evt.Start_Time__c = dt.format('hh:mm a'));

I think the correct workaround is here: Workarounds for Missing Apex Time.format() Instance Method

1
  • Thanks , but i can able to produce this format like "03:15 PM" , but it returns String, i want time as like 03:15 PM . When i'm using this "DateTime.parse(dt.format('hh:mm a')).time()" , it's returning time as format that i want(03:15 PM) but when i'm putting this into evt.Start_Time__c (Time type field) , It's getting error "INVALID date/time". This is the actual problem that i'm facing. Please Help me out , if you know another way to solve this. Oct 23, 2019 at 12:08
0

You have to save Time in your object

Event__c evt = new Event__c();
evt.Start_Time__c = System.now().time();

As there is no Time.Format() , you need a custom method to parse the time and format it in your own way when you want to display it in frontend.

2
  • System.now().format('hh:mm a'); It'll be give String , that we can't put into the time field. Oct 23, 2019 at 9:47
  • @ManishMourya Updated the answer. Oct 23, 2019 at 10:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .