Ejemplos fechas en Java

LocalDate fecha = LocalDate.now();
		System.out.println(fecha);
		System.out.println(fecha.getDayOfMonth());
		System.out.println(fecha.getDayOfYear());
		System.out.println(fecha.getYear());
		
		// Crear una fecha específica
		LocalDate specificDate = LocalDate.of(2023, 5, 14);
		System.out.println(specificDate.getDayOfWeek().getValue());
		
		LocalDate juevesproximo=fecha.plusWeeks(1);
		System.out.println(juevesproximo);
		
		// En temp cojo la fecha de hoy
		LocalDate temp=LocalDate.now();
		temp=LocalDate.of(2023, 1, 1);
		// Miro el mes en el que estamos
		int mes=temp.getMonthValue();
		// Mientras la fecha siga siendo del mismo mes
		while(temp.getMonthValue()==mes) {
			// Si es sábado, imprimo la fecha
			if (temp.getDayOfWeek()==DayOfWeek.SATURDAY) {
				System.out.println("Este día es sábado:"+temp);
				temp=temp.plusDays(7);
			}else {
				temp=temp.plusDays(1);
			}
			// Sumo un día a la fecha
			
		}
		
		temp=LocalDate.of(2023, 8, 15);
		// Formatear
		System.out.println(temp.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
		
		// Parsear
		LocalDate fechaParseada = LocalDate.parse("2022-12-03");
		System.out.println("Fecha parseada: " + fechaParseada);
		// Parsear con un formato determinado
		LocalDate fechaParseada2 = LocalDate.parse("03/12/2023",DateTimeFormatter.ofPattern("dd/MM/yyyy"));
		System.out.println("Fecha parseada: " + fechaParseada2);
		
		// Crear una hora específica
		LocalTime specificTime = LocalTime.of(14, 30,50);
		System.out.println(specificTime);

		// Momento actual
		LocalTime ahora=LocalTime.now();
		System.out.println(ahora);
		
		// Obtener partes de la hora
		System.out.println(ahora.getHour());
		System.out.println(ahora.getMinute());
		System.out.println(ahora.getNano());

		// Añadir o restar partes de tiempo
		LocalTime momento=ahora.plusHours(2);
		System.out.println(momento);
		
		// Podemos parsear una cadena de caracteres
		LocalTime cita=LocalTime.parse("10:00:00");
		System.out.println(cita);
		
		// Crear una fecha y hora específica
		LocalDateTime specificDateTime = LocalDateTime.of(2023, 5, 15, 14, 30);
		System.out.println(specificDateTime);
		
		// Obtener partes de la fecha/hora
		LocalDateTime esteMomento=LocalDateTime.now();
		System.out.println(esteMomento);
		System.out.println(esteMomento.getMonthValue());
		System.out.println(esteMomento.getHour());
		System.out.println(esteMomento.getSecond());
		System.out.println(esteMomento.getDayOfYear());
		
		
		// Sumar y restar partes de tiempo
		esteMomento=esteMomento.plusDays(1);
		esteMomento=esteMomento.plusHours(1);
		System.out.println(esteMomento);
		
		// Parsear una fecha y una hora
		LocalDateTime fechahora=LocalDateTime.parse("2023-11-17T21:12:10");
		System.out.println(fechahora);

Publicado por

Avatar del usuario

Juan Pablo Fuentes

Formador de programación y bases de datos