You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新手求助:如何获取MS SQL Server当前日期时间并在Android TextView显示?

获取MS SQL Server当前时间并在Android TextView显示的解决方案

别担心,这个需求完全可以实现!我来一步步帮你达成目标——核心思路就是先从SQL Server拿到服务器时间,再把这个时间传到Android端显示出来,彻底避开设备本地时间的干扰。

第一步:从MS SQL Server获取当前时间

首先你需要用正确的SQL语句拿到服务器的当前时间,常用的有两个函数,按需选择:

  • GETDATE():返回服务器当前日期时间,精度到毫秒
  • SYSDATETIME():精度更高(到纳秒),推荐使用

执行这条SQL就能拿到结果:

SELECT SYSDATETIME() AS ServerCurrentTime;

如果需要转换为用户所在时区的时间(比如中国标准时间),也可以直接在SQL里处理:

SELECT CONVERT(datetimeoffset, SYSDATETIME()) AT TIME ZONE 'China Standard Time' AS ServerCSTTime;

第二步:Android端获取并显示时间

这里分两种实现方式,我优先推荐后端API中转的方式——直接在Android里连SQL Server会暴露数据库账号密码,非常不安全;如果只是个人测试用,也可以尝试直接JDBC连接,但一定要注意风险。

方式一:通过后端API(推荐)

最佳实践是写一个简单的后端接口(比如用ASP.NET、Java Spring Boot),接口内部调用SQL获取时间,再把时间以JSON格式返回给Android。

示例:ASP.NET Core接口(C#)

[ApiController]
[Route("api/time")]
public class TimeController : ControllerBase
{
    private readonly string _connectionString;

    public TimeController(IConfiguration configuration)
    {
        _connectionString = configuration.GetConnectionString("SqlServer");
    }

    [HttpGet("server")]
    public async Task<IActionResult> GetServerTime()
    {
        using var conn = new SqlConnection(_connectionString);
        await conn.OpenAsync();
        var sql = "SELECT SYSDATETIME() AS ServerTime";
        using var cmd = new SqlCommand(sql, conn);
        var serverTime = await cmd.ExecuteScalarAsync();
        return Ok(new { ServerTime = serverTime });
    }
}

Android端用Retrofit请求接口

  1. 先在build.gradle(Module)里添加依赖:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
  1. 定义Retrofit接口:
public interface TimeApi {
    @GET("api/time/server")
    Call<ServerTimeResponse> getServerTime();
}

class ServerTimeResponse {
    public String ServerTime;
}
  1. 在Activity里发起请求并更新TextView:
// 初始化Retrofit
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("你的后端接口地址,比如http://yourserver.com/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

TimeApi timeApi = retrofit.create(TimeApi.class);

// 发起请求(注意不能在主线程执行网络请求)
timeApi.getServerTime().enqueue(new Callback<ServerTimeResponse>() {
    @Override
    public void onResponse(Call<ServerTimeResponse> call, Response<ServerTimeResponse> response) {
        if (response.isSuccessful() && response.body() != null) {
            String serverTime = response.body().ServerTime;
            // 在主线程更新TextView
            runOnUiThread(() -> {
                TextView timeTextView = findViewById(R.id.tv_server_time);
                timeTextView.setText("服务器当前时间:" + serverTime);
            });
        }
    }

    @Override
    public void onFailure(Call<ServerTimeResponse> call, Throwable t) {
        // 处理请求失败的情况
        runOnUiThread(() -> {
            TextView timeTextView = findViewById(R.id.tv_server_time);
            timeTextView.setText("获取服务器时间失败");
        });
    }
});

方式二:直接用JDBC连接SQL Server(仅测试用)

如果是个人测试项目,不想写后端,可以直接在Android里用JDBC连接SQL Server,但要注意:

  • 必须开启SQL Server的远程连接权限
  • 在AndroidManifest.xml里添加网络权限:<uses-permission android:name="android.permission.INTERNET" />
  • 不能在主线程执行数据库操作,要用到AsyncTask或者Coroutine
  1. 添加JDBC依赖到build.gradle(Module):
implementation 'com.microsoft.sqlserver:mssql-jdbc:12.4.0.jre11'
  1. 用Coroutine实现异步获取时间(Kotlin示例):
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val timeTextView = findViewById<TextView>(R.id.tv_server_time)

        // 协程异步执行
        lifecycleScope.launch(Dispatchers.IO) {
            val serverTime = getSqlServerTime()
            withContext(Dispatchers.Main) {
                timeTextView.text = "服务器当前时间:$serverTime"
            }
        }
    }

    private fun getSqlServerTime(): String? {
        val connectionString = "jdbc:sqlserver://你的服务器地址:1433;databaseName=你的数据库名;user=用户名;password=密码;"
        return try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
            val conn = DriverManager.getConnection(connectionString)
            val sql = "SELECT SYSDATETIME() AS ServerTime"
            val stmt = conn.createStatement()
            val rs = stmt.executeQuery(sql)
            var time: String? = null
            if (rs.next()) {
                time = rs.getString("ServerTime")
            }
            rs.close()
            stmt.close()
            conn.close()
            time
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
}

注意事项

  • 永远不要在生产环境用直接JDBC连接的方式,会泄露数据库凭证,非常危险
  • 如果后端返回的时间是字符串格式,你可以在Android里转换成更友好的显示格式,比如用SimpleDateFormat或者DateTimeFormatter
  • 要处理网络请求失败、数据库连接失败的情况,给用户友好的提示

内容的提问来源于stack exchange,提问作者Alpha Gabriel V. Timbol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:33:32