通过拿map中的出生日期去计算年龄的java代码怎么写
时间: 2024-05-05 14:17:51 浏览: 7
可以使用以下Java代码来计算年龄:
```java
Calendar dob = Calendar.getInstance();
dob.setTime(dateOfBirth);
Calendar today = Calendar.getInstance();
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.MONTH) < dob.get(Calendar.MONTH)) {
age--;
} else if (today.get(Calendar.MONTH) == dob.get(Calendar.MONTH)
&& today.get(Calendar.DAY_OF_MONTH) < dob.get(Calendar.DAY_OF_MONTH)) {
age--;
}
System.out.println("年龄是:" + age);
```
以上代码假设出生日期已经存储在一个名为`dateOfBirth`的`Date`对象中。它使用当前日期和出生日期计算出年龄,并将结果存储在`age`变量中。最后,它将年龄打印出来。
相关问题
在map中拿出生日期的数据,去计算年龄的java代码怎么写
可以这样写:
```java
// 假设生日数据存在一个叫做birthday的Map中
Map<String, String> birthday = new HashMap<>();
birthday.put("张三", "1990-05-20");
// 获取当前日期
Calendar now = Calendar.getInstance();
// 获取出生日期
String birthStr = birthday.get("张三");
// 将出生日期转换为日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date birthDate = sdf.parse(birthStr);
// 计算年龄
Calendar birth = Calendar.getInstance();
birth.setTime(birthDate);
int age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
if (now.get(Calendar.MONTH) < birth.get(Calendar.MONTH)
|| (now.get(Calendar.MONTH) == birth.get(Calendar.MONTH) && now.get(Calendar.DAY_OF_MONTH) < birth.get(Calendar.DAY_OF_MONTH))) {
age--;
}
// 输出年龄
System.out.println("张三的年龄为:" + age);
```
希望能帮到你。
返回map 去重的java代码怎么写
您好,以下是去重map的Java代码示例:
```java
Map<K, V> map = new HashMap<>();
// your map entries
Map<V, K> uniqueMap = new HashMap<>();
for (Map.Entry<K, V> entry : map.entrySet()) {
if (!uniqueMap.containsKey(entry.getValue())) {
uniqueMap.put(entry.getValue(), entry.getKey());
}
}
Map<K, V> result = new HashMap<>();
for (Map.Entry<V, K> entry : uniqueMap.entrySet()) {
result.put(entry.getValue(), entry.getKey());
}
```
此代码段实现了将原始的 `map` 中的值去重,确保在处理后的 `result` Map 中,值是唯一的,而键则是在原始 `map` 中与值关联的唯一键。