Develop > Programming Guide > JavaScript and Service Manager reference > List: JavaScript examples > Example: Updating a field with the current date and time

Example: Updating a field with the current date and time

This JavaScript example demonstrates how to update a field with the current date and time. The script takes a file object (such as system.vars.$L_file or an SCFile object) and a string containing the name of a datetime field in that file, and updates the indicated field with the current date and time.

This script illustrates several key concepts of using JavaScript in HPE Service Manager.

  • How to call the RAD filename function from JavaScript.
  • How to access a field in a record using an expression of the form file[fieldName] where fieldName is a string.
  • How to test the field’s data type.
  • How to return JavaScript date objects when you reference Service Manager datetime fields.
  • How to assign JavaScript date objects to Service Manager datetime fields.
  • How to use SCFile method return codes to test against global properties like RC_SUCCESS.
  • How to obtain a localized error message from a return code value using the RCtoString method.
  • How to pass traditional query strings that are in Service Manager syntax directly to the doSelect method.
  • How to use underscores in JavaScript to reference Service Manager field names containing dots (such as contact.name).

This script demonstrates calling the datetimestamp function. It selects a record from the contacts table and updates the sysmodtime field.

var f = new SCFile( "contacts" );

f.doSelect( "contact.name = \"BROWN, NICHOLAS\"" );

print( "sysmodtime was: " + f.sysmodtime );

datetimestamp( f, "sysmodtime" );

print( "sysmodtime is now: " + f.sysmodtime );

This script demonstrates how passing the wrong kind of field to the datetimestamp function generates an error message.

datetimestamp( f, "contact_name" );

function datetimestamp( file, fieldName )
{
  var fileName;
  var today;
  var fieldType;
  var rc;

  fileName = system.functions.filename( file );
  today    = new Date();

  print( "datetimestamp called for file " + fileName + " and field " + fieldName );

  var d = new SCDatum( file[fieldName] );

  fieldType = d.getType();

  if ( fieldType != "TIME" )
  {
    print( "Error! Field " + fieldName + " is a " + fieldType + " field!
		This function can only be called with date/time fields!" );
    return false;
  }

  file[fieldName] = today;  // Timestamp the field

  rc = file.doUpdate();

  if ( rc != RC_SUCCESS )
  {
    print( "Error " + RCtoString(rc) + " trying to update " + fileName + " record" );
    return false;
  }

  return true;
}