Convertir una cadena a fecha
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class CadenaAFecha { public static void main(String[] args) { System.out.println( "Fecha deseada: " + returnNewFormatOfDate( "041020150510" , "MMddyyyyHHmm" , "yyyy-MM-yyyy HH:mm:ss" )); } public static String returnNewFormatOfDate(String strDate, String sdf1, String sdf2){ String sDate = strDate; try { // creamos un objeto SimpleDateFormat con el formato de fecha de la cadena de origen SimpleDateFormat sdfSource = new SimpleDateFormat(sdf1); // parseamos la cadena en el objeto Date Date date = sdfSource.parse(sDate); // creamos un objeto SimpleDateFormat con el formato de fecha deseado SimpleDateFormat sdfDestination = new SimpleDateFormat(sdf2); // parseamos la fecha en el formato de destino sDate = sdfDestination.format(date); System.out.print( "La fecha se convierte del formato '" + sdf1 + "' al formato '" + sdf2 + "' \n" ); System.out.print( "Fecha en formato cadenas: " + strDate.toLowerCase() + "\n" ); } catch (ParseException pe) { System.out.print( "Parse Exception: " + pe); } return sDate; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import java.util.Calendar; import java.text.SimpleDateFormat; public class ObtenerHoraYFecha { public static void main(String args[]) { System.out.println( "La fecha es: " + getDate()); System.out.println( "La hora es: " + getTime()); } public static String getDate() { String date_format = "yyyy-MM-dd" ; // yyyy-MM-dd HH:mm:ss.SSS SimpleDateFormat sdf = new SimpleDateFormat(date_format); Calendar c1 = Calendar.getInstance(); return sdf.format(c1.getTime()); } public static String getTime() { String DATE_FORMAT = "HH:mm:ss" ; SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); Calendar c1 = Calendar.getInstance(); return sdf.format(c1.getTime()); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class ObtenerHoraYFecha2 { // Obtener hora y fecha public static void main(String[] args) { System.out.println( "getCurrentTimeStamp: " + getCurrentTimeStamp()); } private static java.sql.Timestamp getCurrentTimeStamp() { java.util.Date today = new java.util.Date(); return new java.sql.Timestamp(today.getTime()); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import java.util.Calendar; import java.util.GregorianCalendar; public class ObtenerHoraYFecha3 { public static void main(String[] args) { // Obtener la fecha y hora del sistema Calendar date = new GregorianCalendar(); // el método get obtiene los valores de la fecha int year = date.get(Calendar.YEAR); int month = date.get(Calendar.MONTH); int day = date.get(Calendar.DAY_OF_MONTH); int hour = date.get(Calendar.HOUR_OF_DAY); int minute = date.get(Calendar.MINUTE); int second = date.get(Calendar.SECOND); System.out.println( "Fecha actual: " + day + "/" + (month + 1 ) + "/" + year); System.out.printf( "Hora actual: %02d:%02d:%02d %n" , hour, minute, second); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 | import java.text.SimpleDateFormat; import java.util.Date; public class MilisegundosAFecha { public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.SSS" ); long tiempoEnMilisegundos = 1422980230456L; Date fecha = new Date(tiempoEnMilisegundos); String tiempoRestanteString = sdf.format(fecha); System.out.println( "Milisegundos a fecha: " + tiempoRestanteString); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import java.text.ParseException; import java.util.concurrent.TimeUnit; public class MilisegundosAFecha2 { // Convertir un tiempo dado en milisegundos en formato (hh:mm.ss (ms)) public static void main(String[] args) throws ParseException { long millis = 5816 ; String hms = String.format( "%02d:%02d:%02d (%03d)" , TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis), TimeUnit.MILLISECONDS.toSeconds(millis), millis % 1000 ); System.out.println(hms); } } |
1 2 3 4 5 6 7 8 9 10 | public class DateUtilADateSql { public static void main(String[] args) { java.util.Date utilDate = new java.util.Date(); java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); System.out.println( "UtilDate: " + utilDate); System.out.println( "SqlDate: " + sqlDate); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import java.text.DateFormat; import java.text.SimpleDateFormat; public class UnixTime { // Cambiando la fecha y hora a UNIX TIME public static void main(String[] args) { long epoch = System.currentTimeMillis() / 1000 ; java.util.Date time1 = new java.util.Date(( long ) epoch * 1000 ); DateFormat df = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.SSS" ); String s = df.format(time1); System.out.println( "epoch serializado: " + epoch); System.out.println( "epoch deserializado3: " + time1); System.out.println( "epoch formateado: " + s); } } |
IMAGENES
Descargar imágenes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; /** * Ejemplo de descarga de un fichero de imagen desde la web. * * @author chuidiang * */ public class DescargarImagen { /** * Descarga un fichero jpeg y lo guarda en e:/foto.jpg * * @param args */ public static void main(String[] args) { try { // Url con la foto URL url = new URL( "https://vignette.wikia.nocookie.net/death-battle-fanon-wiki-en-espanol/images/0/09/Goku.png/revision/latest/scale-to-width-down/310?cb=20190222052804&path-prefix=es" ); // establecemos conexion URLConnection urlConnection = url.openConnection(); // sacamos por pantalla el tipo de fichero System.out.println(urlConnection.getContentType()); // se obtiene el inputStream de la foto web y se abre el fichero InputStream is = urlConnection.getInputStream(); FileOutputStream fos = new FileOutputStream( "e:/foto.jpg" ); // lectura de la foto de la web y escritura en fichero local byte [] array = new byte [ 1000 ]; // buffer temporal de lectura. int leido = is.read(array); while (leido > 0 ) { fos.write(array, 0 , leido); leido = is.read(array); } // cierre de conexion y fichero. is.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class RedimensionarImagen { // Ancho máximo public static int MAX_WIDTH = 165 ; // 800=800 165 300 x 190 // Alto máximo public static int MAX_HEIGHT = 165 ; // 800=600 105 public static void main(String[] args) { copyImage( "e:/goku.jpg" , "e:/gokucopia.jpg" ); System.out.println( "Se redimensionó la imagen" ); } /* * Este método recibe la ruta al archivo original y la ruta donde vamos a * guardar la copia copyImage("E:\\Fotos\\test.png","C:\\Copia\\test2.png"); */ public static void copyImage(String filePath, String copyPath) { BufferedImage bimage = loadImage(filePath); if (bimage.getHeight() > bimage.getWidth()) { int heigt = (bimage.getHeight() * MAX_WIDTH) / bimage.getWidth(); bimage = resize(bimage, MAX_WIDTH, heigt); int width = (bimage.getWidth() * MAX_HEIGHT) / bimage.getHeight(); bimage = resize(bimage, width, MAX_HEIGHT); } else { int width = (bimage.getWidth() * MAX_HEIGHT) / bimage.getHeight(); bimage = resize(bimage, width, MAX_HEIGHT); int heigt = (bimage.getHeight() * MAX_WIDTH) / bimage.getWidth(); bimage = resize(bimage, MAX_WIDTH, heigt); } saveImage(bimage, copyPath); } /* * Este método se utiliza para cargar la imagen de disco */ public static BufferedImage loadImage(String pathName) { BufferedImage bimage = null; try { bimage = ImageIO.read(new File(pathName)); } catch (Exception e) { e.printStackTrace(); } return bimage; } /* * Este método se utiliza para almacenar la imagen en disco */ public static void saveImage(BufferedImage bufferedImage, String pathName) { try { String format = (pathName.endsWith(".png")) ? "png" : "jpg"; File file = new File(pathName); file.getParentFile().mkdirs(); ImageIO.write(bufferedImage, format, file); } catch (IOException e) { e.printStackTrace(); } } /* * Este método se utiliza para redimensionar la imagen */ public static BufferedImage resize(BufferedImage bufferedImage, int newW, int newH) { int w = bufferedImage.getWidth(); int h = bufferedImage.getHeight(); BufferedImage bufim = new BufferedImage(newW, newH, bufferedImage.getType()); Graphics2D g = bufim.createGraphics(); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(bufferedImage, 0 , 0 , newW, newH, 0 , 0 , w, h, null ); g.dispose(); return bufim; } } |
OTROS
Obtener IP, HOST y MAC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import java.net.InetAddress; public class ObtenerIPYHOST { public static void main(String[] args) { try { // Obtener ip local InetAddress addr = InetAddress.getLocalHost(); String hostname = addr.getHostName(); String ip = addr.getHostAddress(); System.out.println( "Host: " + hostname); System.out.println( "IP: " + ip); } catch (Exception e) { // TODO: Add catch code e.printStackTrace(); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; public class ObtenerIPYMac { public static void main(String[] args) { InetAddress ip; try { ip = InetAddress.getLocalHost(); System.out.println( "Dirección IP actual: " + ip.getHostAddress()); NetworkInterface network = NetworkInterface.getByInetAddress(ip); byte [] mac = network.getHardwareAddress(); System.out.print( "Dirección MAC actual: " ); StringBuilder sb = new StringBuilder(); for ( int i = 0 ; i < mac.length; i++) { sb.append(String.format( "%02X%s" , mac[i], (i < mac.length - 1 ) ? "-" : "" )); } System.out.println(sb.toString()); } catch (UnknownHostException e) { e.printStackTrace(); } catch (SocketException e) { e.printStackTrace(); } } } |
.
No hay comentarios, ¡cuéntame algo!
Me gustaría saber tu opinión. ¡Saludos!