Java从unix时间戳获取当前日期

时间:2017-07-29 17:37:09

标签: java unix-timestamp

我想将unix时间戳只转换为当天,就像今年当天的当天那样,是否可以只使用数学,如*,/或其他东西?

3 个答案:

答案 0 :(得分:0)

您可以使用SimpleDateFormat格式化日期:

long unixSeconds = 1372339860;
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); // the format of your date
sdf.setTimeZone(TimeZone.getTimeZone("GMT-4")); // give a timezone reference for formating (see comment at the bottom
String formattedDate = sdf.format(date);
System.out.println(formattedDate);

您还可以通过将时间戳乘以1000来将其转换为毫秒:

java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);

完成后,你可以得到你想要的东西:

Calendar cal = Calendar.getInstance();
cal.setTime(dateTime);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH); //here is what you need
int day = cal.get(Calendar.DAY_OF_MONTH);

答案 1 :(得分:0)

您可以使用java.util.Date从unix时间戳计算日期 您需要将时间戳乘以1000,因为java需要毫秒。您可以使用cal.get(Calendar.DAY_OF_MONTH)功能打印当天。

import java.sql.Timestamp;
import java.util.Calendar;

public class MyFirstJavaProgram {
    public static void main(String []args) {
       long unixTimeStamp= System.currentTimeMillis() / 1000L;
       java.util.Date time=new java.util.Date((long)unixTimeStamp*1000);
       Calendar cal = Calendar.getInstance();
       // It's a good point better use cal because date-functions are deprecated
       cal.setTime(time);
       System.out.println(cal.get(Calendar.DAY_OF_MONTH));
    }
}

如有任何问题,请发表评论。

答案 2 :(得分:0)

简短的解决方案就像

 #include<iostream>
 #include<stdio.h>
 using namespace std;
 struct node
 {
     int data;
     struct node* left;
     struct node* right;
 };

 void insert(struct node * root,int k)
{
struct node *n,*pre;
n=(struct node *)malloc(sizeof(struct node));
n->left=NULL;
n->right=NULL;
n->data=k;
if(root==NULL)
 root=n;
else
 {
 pre=root;
 while(pre!=NULL)
 {
    if(k<pre->data)
    {  
        if(pre->left==NULL)
          {
           pre->left=n;
          }
        pre=pre->left;
    }
    else if(k>pre->data)
    {
        if(pre->right==NULL)
          {
             pre->right=n;
          }
        pre=pre->right;
    }

 }

  }
 }
 void traversal(struct node * root)
 {
 if(root!=NULL)
 {
    cout<<root->data<<endl;
    traversal(root->left);
    traversal(root->right);
 }

 }

 int main()
 {
   struct node *root=NULL;
   int i,data;
   while(1)
   {
     cout<<"1.Enter into tree"<<endl;
     cout<<"2.traverse"<<endl;
     cout<<"3.exit"<<endl;
     cin>>i;
     switch(i)
     {
        case 1:cout<<"input a number:";
               cin>>data;
               insert(root,data);
               break;
        case 2:cout<<"The elements of the tree:"<<endl;
               traversal(root);
               break;
        case 3:cout<<"Exiting.... || bye!";
               exit(0);      
               break; 
    }
   }
  }

可以通过计算(*和/)获得此结果,但没有简单的方法。您可以使用java.util.GregorianCalendar的实现作为参考