Java Code Examples for java.util.Date#toString()

The following examples show how to use java.util.Date#toString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebDSLDateBridge.java    From webdsl with Apache License 2.0 6 votes vote down vote up
public synchronized String nonNullDateToString(Date date){

        try {
            switch (resolution) {
              case YEAR: return YEAR.format(date);
              case MONTH:return MONTH.format(date);
              case DAY:  return DAY.format(date);
              case HOUR: return HOUR.format(date);
              case MINUTE: return MINUTE.format(date);
              case SECOND: return SECOND.format(date);
              case MILLISECOND: return MILLISECOND.format(date);
              default: throw new SearchException( "Unable to convert date: '" + date.toString() + "' to String" );
            }
        } catch (Exception ex) {
            org.webdsl.logging.Logger.error( "Unable to convert date: '" + date.toString() + "' to String. Field value not added to index" );
            org.webdsl.logging.Logger.error("EXCEPTION",ex);
            return null;

        }
    }
 
Example 2
Source File: ClientdateTimeResponseTest.java    From cougar with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "TransportType")
public void doTest(CougarClientWrapper.TransportType tt) throws Exception {
    // Set up client
    CougarClientWrapper cougarClientWrapper1 = CougarClientWrapper.getInstance(tt);
    CougarClientWrapper wrapper = cougarClientWrapper1;
    BaselineSyncClient client = cougarClientWrapper1.getClient();
    ExecutionContext context = cougarClientWrapper1.getCtx();
    // Create date to pass to method (and store as a string to validate response against)
    Date date2 = new Date();
    String currentDateString = date2.toString();
    Date currentDate = date2;
    // Make call via rescript transport
    Date responseDate = client.dateTimeSimpleTypeEcho(context, currentDate);
    // Check received date matches the expected date
    String response = responseDate.toString();
    assertEquals(currentDateString, response);
}
 
Example 3
Source File: LogWriterImpl.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Convert a Date to a timestamp String.
 * @param d a Date to format as a timestamp String.
 * @return a String representation of the current time.
 */
public String formatDate(Date d) {
  try {
    synchronized (timeFormatter) {
      // Need sync: see bug 21858
      return timeFormatter.format(d);
    }
  } catch (Exception e1) {
    // Fix bug 21857
    try {
      return d.toString();
    } catch (Exception e2) {
      try {
        return Long.toString(d.getTime());
      } catch (Exception e3) {
        return "timestampFormatFailed";
      }
    }
  }
}
 
Example 4
Source File: ResultSetUtil.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
private static Object convertDateValue(final Object value, final Class<?> convertType) {
    Date date = (Date) value;
    switch (convertType.getName()) {
        case "java.sql.Date":
            return new java.sql.Date(date.getTime());
        case "java.sql.Time":
            return new Time(date.getTime());
        case "java.sql.Timestamp":
            return new Timestamp(date.getTime());
        case "java.lang.String":
            return date.toString();
        default:
            throw new ShardingSphereException("Unsupported Date type: %s", convertType);
    }
}
 
Example 5
Source File: DateUtils.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 返回美国时间格式 26 Apr 2006
 * @param str
 * @return
 */
public static String getEDate(String str) {
	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
	ParsePosition pos = new ParsePosition(0);
	Date strtodate = formatter.parse(str, pos);
	String j = strtodate.toString();
	String[] k = j.split(" ");
	return k[2] + k[1].toUpperCase() + k[5].substring(2, 4);
}
 
Example 6
Source File: DefaultObjectInfo.java    From imagej-server with Apache License 2.0 5 votes vote down vote up
public DefaultObjectInfo(final Object object, final String createdBy) {
	final Date now = new Date();
	createdAt = now.toString();
	this.id = "object:" + Long.toUnsignedString(now.getTime(), 36) + Utils
		.randomString(8);
	this.object = object;
	this.createdBy = createdBy;
	this.lastUsed = null;
}
 
Example 7
Source File: DateUtilsBasic.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 返回美国时间格式 26 Apr 2006.
 * @param str
 *            	时间字符串
 * @return String
 * 				如果传入的字符串为 2011-06-23,则返回 23JUN11
 */
public static String getEDate(String str) {
	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
	ParsePosition pos = new ParsePosition(0);
	Date strtodate = formatter.parse(str, pos);
	String j = strtodate.toString();
	String[] k = j.split(" ");
	return k[2] + k[1].toUpperCase() + k[5].substring(2, 4);
}
 
Example 8
Source File: PrinterOfDate.java    From morpheus-core with Apache License 2.0 5 votes vote down vote up
@Override
public final String apply(Date date) {
    if (date == null) {
        return getNullValue().get();
    } else {
        final DateFormat dateFormat = format.get();
        return dateFormat != null ? dateFormat.format(date) : date.toString();
    }
}
 
Example 9
Source File: LocalizedResource.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getTimeAsString(Date t){
	if (!enableLocalized){
		return t.toString();
	}
	return formatTime.format(t,	new StringBuffer(),
								  new java.text.FieldPosition(0)).toString();
}
 
Example 10
Source File: CompatibilityTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void TestSecondsZero121() {
    Calendar        cal = new GregorianCalendar();
    // Initialize with current date/time
    cal.setTime(new Date());
    // Round down to minute
    cal.set(Calendar.SECOND, 0);
    Date    d = cal.getTime();
    String s = d.toString();
    if (s.indexOf(":00 ") < 0) errln("Expected to see :00 in " + s);
}
 
Example 11
Source File: UnixOSInfo.java    From jHardware with Apache License 2.0 5 votes vote down vote up
private static String normalizeBootUpDate(String rawBootUpdate) {
     DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm yyyy", Locale.ENGLISH);
     Date returnedDate;
     try{
         returnedDate = df.parse(rawBootUpdate + " " + Calendar.getInstance().get(Calendar.YEAR));
     } catch(ParseException pe) {
         return rawBootUpdate;
     }
     
     return returnedDate.toString();
}
 
Example 12
Source File: IndexPage.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public ByteBuf getContent(Client client, String uri) {
   String user = client.getPrincipalName();
   String token = "[no token]";
   String startTime = "[unknown]";
   String expirationTime = "[never]";
   String link;
   
   Date loginTime = client.getLoginTime();
   if(loginTime != null) {
      startTime = loginTime.toString();
   }
   Date expirationDate = client.getExpirationTime();
   if(expirationDate != null) {
      expirationTime = expirationDate.toString();
   }
   
   if(client.isAuthenticated()) {
      link = "<a href='/logout'>Logout</a>";
   }
   else if (serverConfig.getLoginPageEnabled()) {
      link = "<a href='/login'>Login</a>";
   } else {
      link = "";
   }
   
   
   return Unpooled.copiedBuffer(
         String.format(html, user, token, startTime, expirationTime, link),
         Charsets.US_ASCII
   );
}
 
Example 13
Source File: DateTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * java.util.Date#toString()
 */
public void test_toString() {
    // Test for method java.lang.String java.util.Date.toString()
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.DATE, 1);
    cal.set(Calendar.MONTH, Calendar.JANUARY);
    cal.set(Calendar.YEAR, 1970);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    Date d = cal.getTime();
    String result = d.toString();
    assertTrue("Incorrect result: " + d, result
            .startsWith("Thu Jan 01 00:00:00")
            && result.endsWith("1970"));

    TimeZone tz = TimeZone.getDefault();
    TimeZone.setDefault(TimeZone.getTimeZone("GMT-5"));
    try {
        Date d1 = new Date(0);
        String tzShortFormat = isNativeTimeZone("GMT-5") ? "GMT-5" : "GMT-05:00";
        assertTrue("Returned incorrect string: " + d1, d1.toString()
                .equals("Wed Dec 31 19:00:00 " + tzShortFormat + " 1969"));
    } finally {
        TimeZone.setDefault(tz);
    }

    // Test for HARMONY-5468
    TimeZone.setDefault(TimeZone.getTimeZone("MST"));
    Date d2 = new Date(108, 7, 27);
    assertTrue("Returned incorrect string: " + d2, d2.toString()
            .startsWith("Wed Aug 27 00:00:00")
            && d2.toString().endsWith("2008"));
}
 
Example 14
Source File: BackupExport.java    From Clip-Stack with MIT License 4 votes vote down vote up
public static boolean makeExport(Context context, Date startDate, Date endDate, boolean reverse, boolean allItems) {
    Log.v(MyUtil.PACKAGE_NAME, "EXPORT:"+startDate.toString()+endDate.toString());
    if (startDate.after(endDate)) {
        Date tmpDate = startDate;
        startDate = endDate;
        endDate = tmpDate;
    }
    if (!isExternalStorageWritable()) {
        return false;
    }
    List<ClipObject> clipObjects;
    if (allItems) {
        clipObjects = Storage.getInstance(context).getClipHistory();
    } else {
        clipObjects = Storage.getInstance(context).getStarredClipHistory();
    }

    List<String> backupStringList = new ArrayList<>();
    for (ClipObject clipObject : clipObjects) { //delete out of date clips
        Date clipObjectDate = clipObject.getDate();
        String clipTitle = clipObjectDate.toString();
        if (clipObject.isStarred()) {
            clipTitle += ClipObject.markStar;
        }
        if (clipObjectDate.after(startDate) && clipObjectDate.before(endDate)) {
            backupStringList.add("\n" + clipTitle + "\n" + clipObject.getText());
        }
    }

    if (!reverse) { //reverse
        Collections.reverse(backupStringList);
    }

    backupStringList.add(0, context.getString(R.string.backup_file_name)+"\n");

    File backupFile = getBackupStorage(context, new Date());
    try {
        if (!backupFile.exists()) {
            if (!backupFile.createNewFile()) {
                throw new  IOException("Can't create file: " + backupFile.getName());
            }
        }
        BufferedWriter writer = new BufferedWriter(new FileWriter(backupFile, true /*append*/));
        for (String backupString : backupStringList) {
            writer.write(backupString);
        }
        writer.close();
        makeNotification(context, backupFile, true);
        return true;
    } catch (IOException e) {
        Log.e(MyUtil.PACKAGE_NAME, "Backup error: \n" + e.toString());
        makeNotification(context, backupFile, false);
        return false;
    }

}
 
Example 15
Source File: CertificationPanel.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private String getDateInfo(Date date) {
    return date==null?NbBundle.getMessage(CertificationPanel.class, "TXT_NotSpecified"):date.toString();
}
 
Example 16
Source File: JAudioFile.java    From jAudioGIT with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void main(String[] args) throws Exception{
   	processor = new AudioStreamProcessor(args[0],args[1]);

String base_prefix =args[2];
base_prefix += args[4];

ProcessBuilder gstreamerBuilder = new ProcessBuilder("gst-launch-1.0", "-q", "filesrc", "location="+args[3], "!", "decodebin", "!", "audioconvert", "!", "audio/x-raw,format=F32LE", "!", "fdsink");
Process gstreamer =  gstreamerBuilder.start();
       DataInputStream input = new DataInputStream(gstreamer.getInputStream());
ByteBuffer buffer = ByteBuffer.allocateDirect(1000000000);
buffer.order(java.nio.ByteOrder.LITTLE_ENDIAN);
       byte[] b = new byte[1000000];
int read=0;
int total=0;
while((read = input.read(b))>-1){
	total += read;
	if(read > 0)
		buffer.put(b,0,read);
}
System.out.println();
buffer.flip();
FloatBuffer db = buffer.asFloatBuffer();

       double[] samples = new double[total / 8];
for(int i=0;i<samples.length;++i){
	samples[i] = (db.get()+db.get()) / 2.0;
}	
db = null;
       buffer = null;
double max=0.0;
double min=0.0;
boolean okay = false;
if(samples.length < 512){
	throw new Exception("File is too small to analyze - "+samples.length+" samples");
}
for(int i=0;i<samples.length;++i){
		if((samples[i] > 1.0) || (samples[i] < -1.0)){
		throw new Exception("Badly formatted data "+i+" "+samples[i]);
	}
	if((samples[i] > 0.7)){
		okay = true;
	}
}
if(!okay){
	throw new Exception("Data is artificially small - probable endianess problem");
}
processor.process(samples);

Date date = new Date();
       String attach = date.toString();
       attach = Pattern.compile("\\s").matcher(attach).replaceAll("_");
       base_prefix += Pattern.compile(":").matcher(attach).replaceAll("-");
       processor.output(base_prefix);
   }
 
Example 17
Source File: OracleDateSplitter.java    From DBus with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected String dateToString(Date d) {
    // Oracle Data objects are always actually Timestamps
    return "TO_TIMESTAMP('" + d.toString() + "', 'YYYY-MM-DD HH24:MI:SS.FF')";
}
 
Example 18
Source File: AppIdentityServiceTest.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
private String dateDebugStr(String comment, Date date) {
    return comment + "=" + date.toString() + ", " + date.getTime() + ")";
}
 
Example 19
Source File: FileInfoDialog.java    From turbo-editor with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    View view = new DialogHelper.Builder(getActivity())
            .setTitle(R.string.info)
            .setView(R.layout.dialog_fragment_file_info)
            .createSkeletonView();
    //final View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_fragment_file_info, null);

    ListView list = (ListView) view.findViewById(android.R.id.list);

    DocumentFile file = DocumentFile.fromFile(new File(AccessStorageApi.getPath(getActivity(), (Uri) getArguments().getParcelable("uri"))));

    if (file == null && Device.hasKitKatApi()) {
        file = DocumentFile.fromSingleUri(getActivity(), (Uri) getArguments().getParcelable("uri"));
    }

    // Get the last modification information.
    Long lastModified = file.lastModified();

    // Create a new date object and pass last modified information
    // to the date object.
    Date date = new Date(lastModified);

    String[] lines1 = {
            getString(R.string.name),
            //getString(R.string.folder),
            getString(R.string.size),
            getString(R.string.modification_date)
    };
    String[] lines2 = {
            file.getName(),
            //file.getParent(),
            FileUtils.byteCountToDisplaySize(file.length()),
            date.toString()
    };

    list.setAdapter(new AdapterTwoItem(getActivity(), lines1, lines2));


    return new AlertDialog.Builder(getActivity())
            .setView(view)
            .setPositiveButton(android.R.string.ok,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    }
            )
            .create();
}
 
Example 20
Source File: L10NManager.java    From CodenameOne with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Formats a date in a short form e.g. 1/1/2011
 * @param d the date
 * @return the short form string
 */
public String formatDateShortStyle(Date d) {
    return d.toString();
}